问题
I have been looking around for some ways to have my app remember that a user is signed in but could find solutions for Firebase 3. I can login just fine with Firebase authentication but when I quit the app it takes me again to the login. This is closest solution I feel like I have. code snippet This is what I followed from a youtube tutorial. Thanks!
回答1:
You stay logged in with firebase authentication, there's no need to try and re-login users. As long as the user doesn't log out, even if he kills the app, the next time he uses the app, he's automatically logged in. If you want to check if a user is logged in or not, this line of code will get you what you want:
let loggedIn = Auth.auth().currentUser == nil
if loggedIn
is true then don't go to login page
If you want to listen to the authentication state of a user, just add an auth state listener after firebase configuration in AppDeledate
like so:
FirebaseApp.configure()
Auth.auth().addStateDidChangeListener { (auth, user) in
if let currentUser = user {
// Do something with the current user, for example, fetch user info
// Suppose you have a "users" table in your database and each
// user is distinguished by their 'uid' property, then
Database.database().reference()
.child("users/currentUser.uid")
.observe(.value, with: { snapshot in ... })
}
}
Whenever the auth state changes, this code will be executed
BTW, this auth state listener is very helpful when you want to re-render some screens whenever the auth state changes. You can post a notification in the code above using NotificationCenter.default.post(...)
, and receive the notifications in your view controllers
来源:https://stackoverflow.com/questions/49972923/persistence-with-firebase-and-swift-4