简体   繁体   中英

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 (eg 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

  • the difference between Methods 1 and 3
  • what is the app supposed to be doing when 1 and 3 cannot establish a connection? Is it supposed to freeze until a connection is re-established? I worry Methods 1 and 3 might be more prone to crashes. But Method 2 looks out annoyingly often.

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 eg a Facebook would)? If so, with which method can I achieve that?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM