0

In Swift, I am using an observerEventType to retrieve snapshot data from Firebase, and return it in a function. But it appears that the data isn't being saved from the snapshot.

func checkAmount() -> Int {
    var amount = -1

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.rootRef.child("users/").child(NSUserDefaults.standardUserDefaults().stringForKey("id")!).observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
            Amount = (snapshot.value!.objectForKey("CoinAmount") as? Int)!
        })
    })

    return Amount
}

But in my viewDidLoad() function when I do:

if checkAmount() == 0 {
    // You can do this
} else {
    // or you can do that

My logical was that by using dispatch_async I would be able to save the observeEvent (which I was informed is called in the background thread), and use that data in the rest of my program.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    No, that doesn't work in this way, because the call is asynchronous, check this answer is the same: http://stackoverflow.com/questions/38364288/getting-data-out-of-a-closure-that-retrieves-data-from-firebase/38364861#38364861 – José Roberto Abreu Jul 24 '16 at 01:50
  • 1
    As José says: this won't work. If you want to wait for the Firebase data (hint: *you don't*), you will need to use synchronization primitives such as semaphores. See http://stackoverflow.com/questions/34909456/how-to-create-a-function-that-will-eventually-return-some-data-and-caller-must-w/34910535#34910535. There is also no need to async dispatch the Firebase call. The Firebase client already performs all network and disk related activities on a separate thread. It surfaces the callbacks/blocks on the main thread, so that you can interact with the UI. – Frank van Puffelen Jul 24 '16 at 03:29
  • @FrankvanPuffelen "It surfaces the callbacks/blocks on the main thread, so that you can interact with the UI". Is this documented somewhere please? I would really appreciate a link. Also, since in my code I am not doing UI but heavy background work, this is slowing down the UI. Even if I use background process in the callbacks/blocks of firebase observe. Any pointers? – oyalhi Nov 19 '16 at 12:16

0 Answers0