简体   繁体   English

使用Swift从Firebase中获取所有子级的数据

[英]Get the data from all children in firebase using swift

I have a firebase realtime database. 我有一个Firebase实时数据库。 It looks like this: 看起来像这样:

图片

Here is my code: 这是我的代码:

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)
    })

My problem is that my code retrieves the data from only the child called 2 . 我的问题是我的代码仅从名为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! 谢谢你的帮助!

You need to listen to ref 你需要听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)
        }
})

You'll want to attach the observer one level higher in the JSON, and then loop over the child nodes: 您将需要在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)
    }
}

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? Iterate遍历Firebase中的快照子代的循环语法,另请参阅如何在同一循环中一次循环所有Firebase子代? and Looping in Firebase 在Firebase中循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM