bogdan barbulescu bogdan barbulescu - 1 year ago 85
Swift Question

completion handler does not get called as supposed Swift

I am trying to get the uid from a completion handler so that I can construct a path and retrieve some items from my Firebase DB, but

evaluates to nill by the time
gets called.

My issues is that my completion handler is called after
has already been called and not the other way around.
I thought that my code will be executed in line, 1. FIRAuth.auth()?...., 2. dbRef = FIRDatabase....

override func viewDidLoad() {

FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth:FIRAuth, user:FIRUser?) in
if let userSignedIn = user {

self.myuserLogged = userSignedIn.uid
print("Welcome buddy \(self.myuserLogged)")

print("brother \(self.myuserLogged)")

dbRef = FIRDatabase.database().reference().child("Users/\(myuserLogged)")

Answer Source

The completion handler is handled asynchronously, since the operation may take some time. If you need to have dbRef afterwards, you need to put this into the completion handler.

More information: Using closures for asynchronous coding

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download