1

I'm stuck trying figure out how firebase works in swift. Take for example:

    let locationRef = FIRDatabase.database().reference(withPath: "Location")
    print("A")
    locationRef.observeSingleEvent(of: .value, with: { snapshot in
        print("B")
    })
    print("C")

With the firebase database:

{
    "Location" : [ {
        "address" : "100 Foo Avenue",
        "name" : "Foo"
     }, {
        "address" : "1800 Bar Street",
        "name" : "Bar",
     } ]
}

For me, this code will not print B, regardless of where I put the observeSingleEvent (oSE) or what I put inside the oSE . Based on the documentation, I thought that oSE was suppose to trigger once upon running, and then be triggered upon any changes to the firebase database, but I can't get it to trigger. In a previous post here, I did get it to work, but I have no idea how, so some clarification on how oSE triggers would be amazing!

Community
  • 1
  • 1
Michael Eliot
  • 831
  • 8
  • 18
  • Can you update your post with your complete but minimal and relevant JSON structure? – Dravidian Oct 18 '16 at 11:38
  • Does the user running the code have permission to read the data. To detect this, see: http://stackoverflow.com/documentation/firebase/5548/how-do-i-listen-for-errors-when-accessing-the-database/24788/detect-errors-when-reading-data-on-ios#t=201610181337593267146 – Frank van Puffelen Oct 18 '16 at 13:38
  • Once you get your code working, don't be shocked when C prints before B most of the time, if not always. Firebase is asynchronous so the B only happens when Firebase returns the data from the server, which will take much longer than getting to C. – Jay Oct 18 '16 at 17:11

2 Answers2

2

First of all, you are doing it wrong when defining reference. The ref should be FIRDatabase.database().reference().child("Location").

Secondly your knowledge of oSE is right, however you are doing it wrong. Why do you print("A") after defining path?

In conclusion try this:

let locationRef = `FIRDatabase.database().reference().child("Location")`
print("A")
locationRef.observeSingleEvent(of: .value, with: { snapshot in
    print(snapshot.value)//Just to show you what those prints
    print(snapshot.allKeys)//Just to show you what those prints
    print(snapshot.key)//Just to show you what those prints
})
print("C")
Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92
1

If you have an autoID or any unknown ID above your location Dictionary you might wanna use this :-

let locationRef = FIRDatabase.database().reference().queryOrdered(byChild: "Location")
Dravidian
  • 9,945
  • 3
  • 34
  • 74