我想在firebase中捕获我的childByAutoId中的所有值。从本质上讲,它存储了一个人入围的所有项目。然而,我似乎没有捕捉到这一点,我认为这是因为我没有正确地调用快照来考虑自动id。
数据库:
userID
-> Favourited
-> Auto Id
-> itemName: x
-> Auto Id
-> itemName: x
-> Auto Id
-> itemName: x
代码:
func retrieveItems() {
guard let userId = Auth.auth().currentUser?.uid else { return }
let ref = Database.database().reference().child("users/(userId)/Favourited")
ref.observe(.value, with: { (snapshot) in
if snapshot.childrenCount>0 {
self.favUsers.removeAll()
for likes in snapshot.children.allObjects as! [DataSnapshot] {
let likesObject = likes.value as? [String: AnyObject]
let itemName = likesObject!["itemName"]
let likesList = Names(id: likes.key, itemName: itemName as! String?)
self.favUsers.append(likesList)
}
} else {
print("not yet")
}
})
self.favList.reloadData()
}
有没有人看一下,让我知道我可能做错了什么?谢谢你!
这是因为Firebase异步加载数据,而现在你在self.favUsers.append(likesList)
运行之前调用reloadData
。
对reloadData
的调用需要在关闭/完成处理程序中,当数据从Firebase返回时调用:
ref.observe(.value, with: { (snapshot) in
if snapshot.childrenCount>0 {
self.favUsers.removeAll()
for likes in snapshot.children.allObjects as! [DataSnapshot] {
let likesObject = likes.value as? [String: AnyObject]
let itemName = likesObject!["itemName"]
let likesList = Names(id: likes.key, itemName: itemName as! String?)
self.favUsers.append(likesList)
}
self.favList.reloadData() // 👈 Move this here
} else {
print("not yet")
}
})
我还建议您检查一下这些在Firebase中异步数据加载的答案。