Pierre Prevalon Pierre Prevalon - 7 months ago 141
Swift Question

firebase how to get result immediately

I'm trying to create a query in Firebase for my swift iOS app. The problem I'm having with the query is that it does not get the coordinate in the immediately from firebase, unless they are changed. I tried every other observer type, but none appear to work. I know I currently have the observer type to change, but I need the correct way to make it get the location as soon as the app is loaded and also update with firebase.

.childAdded
gets location immediately but it does not update when they are changed on Firebase.

userDirectory.queryOrderedByChild("receiveJobRequest")
.queryEqualToValue(1)
.observeEventType(.ChildChanged , withBlock: {snapshot in
var cIhelperslatitude = snapshot.value["currentLatitude"]
var cIhelperslongitude = snapshot.value["currentLongitude"]

Answer

If you want to listen to multiple event types, you'll need to register multiple listeners.

let query = userDirectory.queryOrderedByChild("receiveJobRequest")
                         .queryEqualToValue(1)

query.observeEventType(.ChildAdded, withBlock: {snapshot in
    var cIhelperslatitude = snapshot.value["currentLatitude"]
    var cIhelperslongitude = snapshot.value["currentLongitude"]

query.observeEventType(.ChildChanged, withBlock: {snapshot in
    var cIhelperslatitude = snapshot.value["currentLatitude"]
    var cIhelperslongitude = snapshot.value["currentLongitude"]

You'll probably want to refactor that common code into a method, that you them call from the .ChildAdded and .ChildChanged blocks.

Alternatively you can register for a .Value event, which is triggered for the initial value and every time the value under the query is changed. But since .Value is invoked with all matching children, you'll have to then loop over the children in your block:

query.observeEventType(.ChildChanged, withBlock: {allsnapshot in
    for snapshot in allsnapshot.children {
        var cIhelperslatitude = snapshot.value["currentLatitude"]
        var cIhelperslongitude = snapshot.value["currentLongitude"]
    }
Comments