[英]Firebase swift - how to print out the value based on a list of specific unique key (unique key stored in array)
// 1。 檢索特定的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。 根據存儲在數組中的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()
}
})
問題有點模糊,但我認為您正在嘗試根據存儲在數組中的ID(密鑰)加載特定產品?
如果是這樣,你不能直接這樣做
這個
.queryEqual(toValue: ArrproductID)
不會起作用,因為ArrproductID是一個數組,而.queryEqual只能排除一個值。
Firebase實時數據庫沒有“IN”查詢。 要實現此目的,您需要迭代數組中的每個值並檢索產品。
假設你的結構看起來像這樣
Products
product_0
ProductName: "Shampoo"
ProductPrice: "$1.99"
ProductImage: "some url"
product_7
ProductName: "Milk"
ProductPrice: "$2.99"
ProductImage: "another url"
然后是用於讀取存儲在數組中的特定產品的代碼
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)
})
}
}
而輸出是
Shampoo $1.99 some url
Milk $2.99 another url
請記住,Firebase通常不建議在緊密循環中迭代觀察。 這可能會阻止主線程並阻止關閉更新UI。 如果它是一個小數據集,那么它應該不是問題。
如果它是一個更大的數據集,這里可能是更好的方法來構建您的數據,以獲得您想要的結果。 例如,如果您想獲得所有頭發護理產品,那么為每個孩子添加一個字段,如'ProductCategory',其值為'Hair Care',這樣您就可以輕松查詢所有Hair Care產品的Products節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.