persistence with Firebase and swift 4 [duplicate]

心已入冬 提交于 2020-11-29 03:11:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!