在 ChildByAutoId 下从 Firebase 检索数据并添加到数组 - Xcode - Swift
Posted
技术标签:
【中文标题】在 ChildByAutoId 下从 Firebase 检索数据并添加到数组 - Xcode - Swift【英文标题】:Retrieving Data from Firebase under ChildByAutoId and adding to array - Xcode - Swift 【发布时间】:2020-01-29 09:03:05 【问题描述】:这是我的 Firebase 数据库:
我正在尝试获取“Tgb9MyxTfdTRd9tQhInsjNRXoPL2”下所有购买和数量的数据并添加到数组中。
这是我的代码:
func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ())
Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: (snapshot) in
guard let dict = snapshot.value as? [String: Any] else return
print("dict-->", dict)
let purchase = Purchase(uid: uid, dictionary: dict)
print("purchase-->", purchase)
completion(purchase)
) (err) in
print("Failed to fetch purchase from database:", err)
这是print("dict-->", dict)
的打印输出:
dict--> ["-LzjaFBgD3ATl7e8uR2-":
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMjEyODM=";
quantity = 1;
, "-LzjaFBiAmrj4m3ZS8m4":
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMDk2OTk=";
quantity = 2;
]
这是print("purchase-->", purchase)
的打印输出:
purchase--> Purchase(uid: "Tgb9MyxTfdTRd9tQhInsjNRXoPL2", purchases: "", quantities: "")
value dict 保存了我需要的数据,但我无法将数据放入数组中显示?
如何将采购和数量数据放入他们自己的数组中?
请帮忙!
【问题讨论】:
【参考方案1】: func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ())
Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: (snapshot) in
if snapshot.childrenCount > 0
self.YourArrayList.removeAll()
for dict in snapshot.children.allObjects as! [DataSnapshot]
let purchase = Purchase(uid: uid, dictionary: dict)
self.YourArrayList.append(purchase)
completion(purchase)
) (err) in
print("Failed to fetch purchase from database:", err)
【讨论】:
for 循环中的 i 在哪里? 不是什么大问题,但您已将所有快照子节点转换为[DataSnapshot]
(即点对点),但您的循环变量称为dict
,这看起来有点误导就像 Purchase 对象期望的是 Dictionary
,而不是 DataSnapshot
。为了清楚起见,可能应该将其称为 childSnap 或 snap 或将其转换为 dict [String: Any]
。除此之外,很好的答案。以上是关于在 ChildByAutoId 下从 Firebase 检索数据并添加到数组 - Xcode - Swift的主要内容,如果未能解决你的问题,请参考以下文章
检索存储在 childByAutoId() 参考 (Swift) 中的特定 Firebase 数据
如何快速从 childByAutoID() 获取密钥 [重复]
Firebase:从实时数据库中检索 childByAutoID
Firebase childbyAutoId 每次都返回相同的奇怪键
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - 在 vue.js 中调用 Fireba