I\'m building an app using Firebase with an initial SignInViewController
that loads a sign in page for users to authenticate with email which triggers the follo
GIDSignIn.sharedInstance().signOut()
Some answers are using a force unwrap when the firebase signing out method can throw an error. DO NOT DO THIS!
Instead the call should be done in a do - catch - block as shown below
do {
try Auth.auth().signOut()
} catch let error {
// handle error here
print("Error trying to sign out of Firebase: \(error.localizedDescription)")
}
You can then listen to the state change using Auth.auth().addStateDidChangeListener and handle accordingly.
I actually had this issue as well. I was also logging out the user (as you are) with the method's provided by Firebase but when I printed to the console it said that I still had a optional user.
I had to change the logic of setting the current user so that it is always configured by the authentication handler provided by Firebase:
var currentUser: User? = Auth.auth().currentUser
var handle: AuthStateDidChangeListenerHandle!
init() {
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
self.currentUser = user
if user == nil {
UserDefaults.standard.setValue(false, forKey: UserDefaults.loggedIn)
} else {
UserDefaults.standard.setValue(true, forKey: UserDefaults.loggedIn)
}
}
}
As long as you are referencing the current user from this handle, it will update the current user no matter the authentication state.
Use exclamation points not question marks.
try! FIRAuth.auth()!.signOut()
You can add a listener in your viewDidAppear
method of your view controller like so:
FIRAuth.auth()?.addStateDidChangeListener { auth, user in
if let user = user {
print("User is signed in.")
} else {
print("User is signed out.")
}
}
This allows you to execute code when the user's authentication state has changed. It allows you to listen for the event since the signOut
method from Firebase does not have a completion handler.
I just had what I think is the same problem - Firebase + Swift 3 wouldn't trigger stateDidChangeListeners
on logout, which left my app thinking the user was still logged in.
What ended up working for me was to save and reuse a single reference to the FIRAuth.auth()
instance rather than calling FIRAuth.auth() each time.
Calling FIRAuth.auth()?.signOut()
would not trigger stateDidChangeListeners
that I had previously attached. But when I saved the variable and reused it in both methods, it worked as expected.