Get the data from all children in firebase using swift

旧街凉风 提交于 2019-12-25 01:38:34

问题


I have a firebase realtime database. 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. 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!


回答1:


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

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




回答2:


You need to listen to 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)
        }
})


来源:https://stackoverflow.com/questions/56638755/get-the-data-from-all-children-in-firebase-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!