AJGronevelt
AJGronevelt

Reputation: 561

Firebase iOS user authentication: avoiding getting logged out of app

Throughout my app, I am using two ways of getting the current userID at any given time. Both of them I have picked up somewhere and (as far as I can tell) work largely fine. And then I use Method 3 as a variation of Method 2.

Method 1:

if let user = Auth.auth().currentUser{
  let uid = user.uid
}

Method 2:

handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  if let user = user {
            // User is signed in.
    self.USER   = user
    self.userID = self.USER?.uid

   } else {
            // No user is signed in.
     let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginScreen")
     self.present(vc!, animated: true, completion: nil) 

 }

Method 3:

handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  if let user = user {
            // User is signed in.
    self.USER   = user
    self.userID = self.USER?.uid

   } else {
            // No user is signed in.
 }

Now it seems that Method 1 and 3 work largely equivalently, while Method 2 sends me back to the Login screen more often (e.g. when the phone goes from 3G to Wifi or flight mode).

Given that I would like my app to stay logged in for long (even when going to the background and coming back) that would suggest using Method 1 or 3. However, I don't quite understand

Generally, once a user has authenticated correctly with Firebase, is there ever a reason for the app to go back to a Login screen? Can the user not stay logged in for arbitrary periods of time (as e.g. a Facebook would)? If so, with which method can I achieve that?

Upvotes: 2

Views: 575

Answers (1)

Niamh
Niamh

Reputation: 56

Just picking up on a couple of points you have raised first, you mention the app freezing when method 2 and 3 are called. Where are you calling these? You need to ensure that these are run on the main thread so that they don't interfere with your UI given it's an asynchronous function.

Also, are you removing the state change listener once logged in? Within your login VC you could have:

deinit {
  if let handle = handle {
    Auth.auth().removeStateDidChangeListener(handle)
  }
}

Furthermore, you can use the GIDSignIn.sharedInstance().signInSilently() method.

Take a look at the iOS friendly chat sample, they have a good login flow and handle the user already being logged in quite well. https://codelabs.developers.google.com/codelabs/firebase-ios-swift/#0

Upvotes: 3

Related Questions