我有一个像这样的火力数据库(Json):
{
"user" : {
"UVHpZfD60EWcYDbeV60ENqXaioA3" : {
"email" : "thisisanothertest@gg.gg",
"location" : {
"latitude" : 37.785834,
"longitude" : -122.406417
},
"profile" : {
"alter" : "23",
"geschlecht" : "männlich",
"name" : "Mario1"
}
},
"nEsKd9uIOnSmVuMbAK0K2X1Dz6A3" : {
"email" : "thisisatest@gg.gg",
"location" : {
"latitude" : 37.785834,
"longitude" : -122.406417
},
"profile" : {
"alter" : "23",
"geschlecht" : "männlich ",
"name" : "Mario"
}
}
}
问题: 现在我想从所有用户(纬度和经度)获取位置,以便稍后将它们放在地图上。 通过执行以下代码,我可以轻松获得单个用户的位置。但是我怎么能一次从所有用户那里获得数据呢?
var ref: DatabaseReference!
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("user").child(userID!).child("location").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let lat = value?["latitude"] as? Double ?? 0.0
let long = value?["longitude"] as? Double ?? 0.0
我发现了一个类似的问题here
所以我尝试了以上链接中的代码:
let usersRef = ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! [String:AnyObject] //child data
let location = userDict["Location"] as! String
print("key = \(uid) is at location = \(location)")
}
})
但是,通过这些代码,我只能得到所有的电子邮件地址。通过更改"位置"发送电子邮件"。如何进入另一个节点以访问"位置"节点并获取所有用户的经纬度?
谢谢:)
答案 0 :(得分:0)
看起来你拼错了字典的location
密钥:
let location = userDict["Location"] as! [String: AnyObject]
将其替换为:
let location = userDict["location"] as! [String: AnyObject]
您始终可以在打印行中设置断点,并在控制台中使用po location
查看您的位置字典的外观。
答案 1 :(得分:0)
正如您在数据中看到的那样location
被存储为另一个对象,因此您必须将其转换为Dictionary
=> [String:AnyObject]
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! [String:AnyObject] //child data
let location = userDict["location"] as! [String:AnyObject]
print("key = \(uid) is at location = \(location)")
}