0

My project is using https://www.firebase.com as backend for a Swift app. I tried to addObject to my NSMutableArrayvariable in order to use it for my table cell.

So I can retrieve data correctly inside .observeEventType() from the Firebase API but outside that my NSMutableArrayalways empty.

Here is my code

// Create a reference to a Firebase location

var bidRef = Firebase(url:"https://xxxx.firebaseio.com/xxx")

println("firebase test")

// Read data and react to changes
var handle = bidRef.queryOrderedByChild("tableCurrentPrice")
                   .observeEventType(.ChildAdded, withBlock: { snapshot in

    self.pubDataArray.addObject(snapshot.value)
    println(self.pubDataArray[0]["tableCurrentPrice"]) //Return Optional(Value)

}, withCancelBlock: { error in
    println(error.description)
})

//bidRef.removeObserverWithHandle(handle)

println(self.pubDataArray[0]["tableCurrentPrice"]) // Error empty array
println(self.pubDataArray.count) // Return Nothing

Anyone knows how to fix this?

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
Varis Darasirikul
  • 2,663
  • 5
  • 22
  • 35
  • The data is loaded asynchronously, so won't be available immediately when you fire `.observeEventType`. So your code block will be executed later, once the data is available (or any time the data gets updated). In the meantime, iOS will continue executing the code, including your `println`. And when that executes: the data simply isn't available yet. This is the normal way of interacting with asynchronous data and you normally "fix it" by moving your `println`s *inside* the callback block. I'll see if it's been covered before for iOS. – Frank van Puffelen Apr 09 '15 at 16:01
  • This question links to both ways of handling this: moving your code *into* the block (as mentioned in my first comment) and waiting for the result with a semaphore: http://stackoverflow.com/questions/28359465/is-there-a-way-to-wait-for-a-query-to-be-finished-in-firebase – Frank van Puffelen Apr 09 '15 at 16:02
  • possible duplicate of [How do I wait for an asynchronously dispatched block to finish?](http://stackoverflow.com/questions/4326350/how-do-i-wait-for-an-asynchronously-dispatched-block-to-finish) – Frank van Puffelen Apr 09 '15 at 16:03

0 Answers0