我正在尝试在Firebase数据库中检索所有用户的 firstnames 。将它们添加到数组的最佳方法是什么?
-Users
-UserId1
- firstname: James
-UserId2
- firstname: Jennifer
let rootRef = Database.database().reference()
let query = rootRef.child("Users").queryOrdered(byChild: "firstname")
query.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let value = snapshot.value as? NSDictionary
let firstname = value?["firstname"] as? String ?? ""
print(firstname)
}
}
答案 0 :(得分:2)
可能只是一个错字;)您应该在循环中使用child
而不是snapshot
。例如,尝试替换以下行:
let value = snapshot.value as? NSDictionary
使用:
let value = child.value as? NSDictionary