如何使用Firebase和Swift从所有用户检索数据

问题描述 投票:0回答:2

我有一个像这样的火基数据库(Json):

       {
  "user" : {
    "UVHpZfD60EWcYDbeV60ENqXaioA3" : {
      "email" : "[email protected]",
      "location" : {
        "latitude" : 37.785834,
        "longitude" : -122.406417
      },
      "profile" : {
        "alter" : "23",
        "geschlecht" : "männlich",
        "name" : "Mario1"
      }
    },
    "nEsKd9uIOnSmVuMbAK0K2X1Dz6A3" : {
      "email" : "[email protected]",
      "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)")
    } 
})

但是,通过这些代码,我只能获得所有的电子邮件地址。通过将“位置”更改为“电子邮件”。如何进入另一个节点以访问“位置”节点并获取所有用户的经度和纬度?

谢谢 :)

swift firebase firebase-realtime-database
2个回答
0
投票

看起来你拼错了location密钥为你的字典:

let location = userDict["Location"] as! [String: AnyObject]

替换为:

let location = userDict["location"] as! [String: AnyObject]

您始终可以在打印行中设置断点,并在控制台中查看po location的位置字典。


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)")
} 
© www.soinside.com 2019 - 2024. All rights reserved.