bogdan barbulescu bogdan barbulescu - 3 months ago 13
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

myuserLogged
evaluates to nill by the time
dbRef
gets called.

My issues is that my completion handler is called after
dbRef
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() {
super.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)")
startObservingDB()
}

Answer

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