0

I'm trying to access the current logged in user's username and store that into a variable.


    self.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
        self.currentUser = (snapshot.value.objectForKey("users")?.objectForKey(self.ref.authData.uid)?.objectForKey("username") as! String)
    })
    print(“self.currentUser”)
But any code before observeSingleEventOfType() will be executed, then any code after that function will be executed. So this will execute the print statement before retrieving the username. Why does that happen and how can I use the result of that snapshot outside of that function?
Striving
  • 35
  • 8
  • You cannot return data now, that is still being loaded. See http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function, http://stackoverflow.com/questions/27081062/swift-how-do-i-return-a-value-within-an-asynchronous-urlsession-function, http://stackoverflow.com/questions/31794542/ios-swift-function-that-returns-asynchronously-retrieved-value – Frank van Puffelen Feb 16 '16 at 06:46

1 Answers1

1

You want to move the print("self.currentUser") inside the closure/block.

The code inside the closure/block will execute whenever it's ready, in your case I assume whenever the value you're listening for changes. Everything before and after the observeSingleEventOfType will execute in order.

David Chavez
  • 381
  • 3
  • 5
  • I need use the currentUser variable in other functions outside of observeSingleEventOfType() in functions below this, but the code beneath this function keeps getting executed first. – Striving Feb 16 '16 at 06:43