I'm working with Firebase and per their docs, I'm checking to see whether or not a user's logged in state changes. The problem resides in the listener block, where the code is being called twice when the apps launched (user's logged in). It's not too much of a deal, but Firebase is creating two values in connections and removing both. How would I fix this issue? I'd need to call it after the user is obtained in the listener though and not outside because there is no guarantee that user will exist outside that block if it's not finished getting the user data first.
FIRAuth.auth()?.addAuthStateDidChangeListener { auth, user in
if let theUser = user {
// User is signed in.
// CODE IN HERE IS CALLED TWICE UPON APP LAUNCH (WHEN USERS LOGGED IN).... WHY?
self.currentUser = theUser
print("LOGGED IN!!!!")
self.updateUsersStatus(user: self.currentUser)
} else {
// No user is signed in.
self.performSegueWithIdentifier(SEGUE_LOG_IN, sender: self)
}
}
I ran into the same issues as reported by Jamie22. Strange thing - I got two similar app setups, but only one app calls the auth state listener method twice on change.
This workaround is what solved the issue for me:
var activeUser:FIRUser!
override func viewDidLoad() {
super.viewDidLoad()
FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth:FIRAuth, user:FIRUser?) in
if let user = user {
if(self.activeUser != user){
self.activeUser = user
print("-> LOGGED IN AS \(user.email)")
}
} else {
print("-> NOT LOGGED IN")
}
})
}
By checking if the appUser has changed on auth state change, you can get rid of the second call, because it will be equal to the user you get in the first call.
⌘ + click or option + click on the addAuthStateDidChangeListener
function. You will see the following:
Registers a block as an "auth state did change" listener. To be invoked when:
- The block is registered as a listener,
- The current user changes, or,
- The current user's access token changes.
To summarize - the block get's called immediately and then most likely gets called again after verifying the FIRApp and/or FIRAuth objects do not contain any stale data. So the behavior of invoking the callback twice should be expected and managed appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With