我有一个Firebase实时数据库。看起来像这样:
这是我的代码:
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
的孩子那里检索数据。如何使它从所有孩子那里检索数据?
如果您有任何疑问,请告诉我。感谢您的帮助!
答案 0 :(得分:1)
您需要听ref
ref.observeSingleEvent(of: .value, with: { snapshot in
guard let dict = snapshot.value as? [String:[String:Any]] else {
print("Error")
return
}
Array(dict.values).forEach {
let latitude = $0["Latitude"] as? String
let longtitude = $0["Longtitude"] as? Int
print(longtitude)
print(latitude)
}
})
答案 1 :(得分:1)
您将要在JSON中将观察者附加上一层,然后在子节点上循环:
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)
}
}
取自Iterate over snapshot children in Firebase的循环语法,另请参见How do I loop all Firebase children at once in the same loop?和Looping in Firebase