Dani Kovács
Dani Kovács

Reputation: 131

Get the data from all children in firebase using swift

I have a firebase realtime database. It looks like this:

Image

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!

Upvotes: 2

Views: 1646

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

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

Upvotes: 6

Shehata Gamal
Shehata Gamal

Reputation: 100503

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

Upvotes: 1

Related Questions