How to maintain user session after exiting app in Firebase

12,921

Firebase should already be keeping track of your user through app launches.

Your issue could be with using FIRAuth.auth()?.currentUser? directly rather than the recommended approach.

The recommended way to get the current user is by setting a listener on the Auth object:

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

By using a listener, you ensure that the Auth object isn't in an intermediate state—such as initialisation—when you get the current user.

In my own application, I use both. If the user doesn't exist with the first method, it moves onto the second, and if that fails, present login/signup screen.

Share:
12,921
Lavvo
Author by

Lavvo

Updated on June 05, 2022

Comments

  • Lavvo
    Lavvo almost 2 years

    I have an app using Firebase as backend. My App implements Firebase-Authentication API using simple Email and Password login for authenticating.

    Everything works fine except for one issue. I would like to maintain the user session even after a user closes the App.

    FIRAuth.auth()?.currentUser? has all the user properties (ex: uid, email, token etc...) for the current user which works great. The problem I noticed is that FIRAuth.auth()?.currentUser? is not persistent. So after exiting the app and launching again, it returns null.

    I would not like to ask a user every time they open the app to login again. Is there a way around this?

  • Lavvo
    Lavvo almost 8 years
    Ah! I just tried this approach and you are absolutely correct. I figured I had to be missing something. Thanks so much for responding.
  • Patroclus
    Patroclus almost 7 years
    Where should I put this conditon? If not in login viewcontroller?
  • Beau Nouvelle
    Beau Nouvelle almost 7 years
    Wherever you like. Anywhere you need to get the current user. Personally I wrap all this code in my own classes.