2

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!

Trevor Reid
  • 3,310
  • 4
  • 27
  • 46
Dani Kovács
  • 131
  • 1
  • 1
  • 7

2 Answers2

5

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

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)
        }
})
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87