Dan Levy Dan Levy - 1 year ago 99
iOS Question

Logging a user out with Firebase 3 and Swift still shows the `currentUser`

I am trying to log a user out with Firebase 3 in my iOS application. Here is my code:

do {


try FIRAuth.auth()?.signOut()

print("FIRUSER - \(FIRAuth.auth()?.currentUser)")

self.performSegueWithIdentifier("logOutSegue", sender: self)

} catch let logOutError {

print("Error Logging User Out - \(logOutError)")

What I am trying to do is perform a segue back to the login screen if a user is successfully logged out. In order to check if a user was logged out, I print
to see if there is still one. I hit the
button and the segue works (no catch -> no error), but when the
print("FIRUSER - \(FIRAuth.auth()?.currentUser)")
code runs, I still get a currentUser. Why is the user not being logged out?

Answer Source

Use cmd+click on the signOut() of try FIRAuth.auth()?.signOut() and you will be directed to its documentation , There you will see

  • @param listener The block to be invoked. The block is always invoked asynchronously on the main thread, even for it's initial invocation after having been added as a listener.

  • @remarks The block is invoked immediately after adding it according to it's standard invocation semantics, asynchronously on the main thread.

Asynchronously which means that your query for signing out the user is loaded in a separate thread in the network link, Which takes time (maybe only milliseconds, but still..) and your print line executes even before it has logged user out.Thats the reason why you still receive the currentUser from firebase...:)

Try printing the currentUser in the viewWillAppear(animated:Bool) of the class where you migrate to after performing segue, if it signs out w/o catching any error's, print line must show you nil.

PS:- Hypothetically speaking if the signOut() function had a completionBlock: , and you tried printing the currentUser there , you probably would had found nil, and probably crashed your app...Again this is just hypothetical

BTW :- Best way to get the current user is by setting a listener on the Auth object

  FIRAuth.auth()?.addAuthStateDidChangeListener { auth, user in
          if let user = user {
              // User is signed in.
           } else {
             // No user is signed in.

Firebase Docs :- Get Current User - Firebase Docs

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