简体   繁体   English

Firebase swift - 如何根据特定唯一键列表打印出值(存储在数组中的唯一键)

[英]Firebase swift - how to print out the value based on a list of specific unique key (unique key stored in array)

//1. // 1。 retrieve specific id and store in array 检索特定的id并存储在数组中

let uid = Auth.auth().currentUser?.uid
        Database.database().reference().child("users").child(uid!).child("cart").observeSingleEvent(of: .value, with: { (snapshot) in


        if let snapDict = snapshot.value as? [String:AnyObject]{

            for each in snapDict as [String:AnyObject]{

                let refID = each.value["refID"] as! String
                self.ArrproductID.append(refID) //append to array

            }
             //print(self.ArrproductID)
        }

    })
    { (error) in
        print(error.localizedDescription)
    }

//2. // 2。 retrieve data from firebase based on the id stored in array 根据存储在数组中的id从firebase检索数据

    refProduct = (Database.database().reference().child("Product").queryOrderedByKey().queryEqual(toValue: ArrproductID) as! DatabaseReference)

    refProduct.observe(DataEventType.value, with:{(snapshot) in
        if snapshot.childrenCount>0{
            self.productList.removeAll()

            for Product in snapshot.children.allObjects as![DataSnapshot]{

                let productObject = Product.value as? [String: AnyObject]
                let ID = Product.key
                let ProductName = productObject?["ProductName"]
                let ProductPrice = productObject?["ProductPrice"]
                let ProductImage = productObject?["ProductImage"]



                //refer to the productmodel.swift? //2. store into model?
                let product = ProductModel( ProductId: ID as String?, ProductName: ProductName as! String? , ProductPrice: ProductPrice as! String?, ProductImage: ProductImage as! String?)


                //3. apend all product to list
                self.productList.append(product)



            }
            //reload all the data?
            self.CartItemView?.reloadData()


        }
    })

The question is a bit vague but I think you are trying to load specific products based on ID's (keys) stored in an array? 问题有点模糊,但我认为您正在尝试根据存储在数组中的ID(密钥)加载特定产品?

If so, you can't do that directly 如果是这样,你不能直接这样做

This 这个

.queryEqual(toValue: ArrproductID)

will not work as ArrproductID is an array and .queryEqual only excepts a single value. 不会起作用,因为ArrproductID是一个数组,而.queryEqual只能排除一个值。

Firebase Realtime Database doesn't have an 'IN' query. Firebase实时数据库没有“IN”查询。 To accomplish this, you'll need to iterate over each value in the array and retrieve the product. 要实现此目的,您需要迭代数组中的每个值并检索产品。

Assuming your structure looks like this 假设你的结构看起来像这样

Products
   product_0
      ProductName: "Shampoo"
      ProductPrice: "$1.99"
      ProductImage: "some url"
   product_7
      ProductName: "Milk"
      ProductPrice: "$2.99"
      ProductImage: "another url"

and then the code to read specific products stored in an array 然后是用于读取存储在数组中的特定产品的代码

func getProducts() {
    let productArray = ["product_0", "product_7"]
    let productsRef = self.ref.child("Products")

    for productId in productArray {
        let thisProductRef = productsRef.child(productId)
        thisProductRef.observeSingleEvent(of: .value, with: { snapshot in
            let name = snapshot.childSnapshot(forPath: "ProductName").value as? String ?? "No Name"
            let price = snapshot.childSnapshot(forPath: "ProductPrice").value as? String ?? "$0.00"
            let image = snapshot.childSnapshot(forPath: "ProductImage").value as? String ?? "No Image"
            print(name, price, image)
        })
    }
}

and the output is 而输出是

Shampoo $1.99 some url
Milk $2.99 another url

Keep in mind that Firebase generally doesn't recommend iterating over observes in a tight loop. 请记住,Firebase通常不建议在紧密循环中迭代观察。 That may block the main thread and prevent closures from updating the UI. 这可能会阻止主线程并阻止关闭更新UI。 If it's a small dataset then it should not be an issue. 如果它是一个小数据集,那么它应该不是问题。

If it's a larger dataset, here may be better ways to structure your data to get the results you want. 如果它是一个更大的数据集,这里可能是更好的方法来构建您的数据,以获得您想要的结果。 For example, if you want to get all hair care products, adding a field to the each child like 'ProductCategory' with a value of 'Hair Care' would then enable you to easily query the Products node for all Hair Care products. 例如,如果您想获得所有头发护理产品,那么为每个孩子添加一个字段,如'ProductCategory',其值为'Hair Care',这样您就可以轻松查询所有Hair Care产品的Products节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM