0

I am using Firebase to store data, and when I try to retrieve data using their closures functions always finish and return before the closure finishes. In my HeyUser class i am trying to get the values in the Friend key in my Firebase and store it in a class property. However when trying to instantiate the object of the class the object is instantiated without getting the values of the Friends key. I was wondering if you are able to delay the instantiation or the completion of a function until the closure is completed. The following is the code of my HeyUser class:

class HeyUser {
var Friends: [String] = [String]()
var username = PFUser.currentUser().username
var ref = Firebase()
var fRef = Firebase()

init() {
    self.ref = Firebase(url: "https://hey-chat.firebaseio.com/").childByAppendingPath("users").childByAppendingPath(PFUser.currentUser().username)
    self.fRef = self.ref.childByAppendingPath("friends")
    self.getFriends()
}

func getFriends() {
    self.fRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
        self.Friends = snapshot.value as [String]
        print("TEST")
        print(self.Friends.count)
        })
}

}

jscs
  • 63,694
  • 13
  • 151
  • 195

1 Answers1

1

I'm not familiar with FireBase, and still getting started with Swift, but I can tell you that this is how async networking works.

You call a function and pass in a block (closure). The function returns immediately, and at some future date, when the network transaction is complete, the framework (firebase in this case) invokes your closusure.

You have to change your thinking in using this architecture. You write your code to send a request and then go into "standby mode", waiting for the request to complete.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Yeah i understand this, but I am wondering how one would go into a standby mode. If you know how to do this in obj c then that is fine I can translate it to swift. Thanks – user2464778 Dec 18 '14 at 17:26
  • You just have your app go back to waiting for input from the user. You do need to add code that prevents the user from sending the same request again before the first request completes, and possibly prevent the user from doing anything else that would cause the current request to fail unless he/she cancels the current transaction first. The specifics depend on your app, so it's hard to give you concrete info. – Duncan C Dec 18 '14 at 20:28