使用swift从firebase中的所有孩子那里获取数据 [英] Get the data from all children in firebase using swift
问题描述
我有一个 firebase 实时数据库.它看起来像这样:
I have a firebase realtime database. It looks like this:
这是我的代码:
ref.child("2").observeSingleEvent(of: .value, with: { snapshot in
guard let dict = snapshot.value as? [String:Any] else {
print("Error")
return
}
let latitude = dict["Latitude"] as Any
let longtitude = dict["Longtitude"] as Any
print(longtitude)
print(latitude)
})
我的问题是我的代码仅从名为 2
的子级检索数据.我怎样才能让它从所有孩子那里检索数据?
My problem is that my code retrieves the data from only the child called 2
. How can I make it retrieve the data from all the children?
如果您有任何问题,请告诉我.感谢您的帮助!
If you have any questions just let me know. Thanks for any help!
推荐答案
您需要在 JSON 中附加上一层的观察者,然后循环遍历子节点:
You'll want to attach the observer one level higher in the JSON, and then loop over the child nodes:
ref.observeSingleEvent(of: .value) { snapshot in
for case let child as FIRDataSnapshot in snapshot.children {
guard let dict = child.value as? [String:Any] else {
print("Error")
return
}
let latitude = dict["Latitude"] as Any
let longtitude = dict["Longtitude"] as Any
print(longtitude)
print(latitude)
}
}
取自 在 Firebase 中迭代快照子项的循环语法,但也见 我如何循环所有Firebase 子项同时在同一个循环中? 和 在 Firebase 中循环
Loop syntax taken from Iterate over snapshot children in Firebase, but also see How do I loop all Firebase children at once in the same loop? and Looping in Firebase
这篇关于使用swift从firebase中的所有孩子那里获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!