Firebase和Swift 4的持久性 [英] persistence with Firebase and swift 4

查看:90
本文介绍了Firebase和Swift 4的持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一些方法让我的应用记住用户已登录,但可以找到Firebase 3的解决方案.我可以使用Firebase身份验证很好地登录,但是当我退出该应用后,它又带我去了.登录.这是我觉得最接近的解决方案. 代码段 这是我从youtube教程中学到的. 谢谢!

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!

推荐答案

您使用Firebase身份验证保持登录状态,无需尝试重​​新登录用户.只要用户不注销,即使他杀死了该应用程序,下次使用该应用程序时,他也会自动登录.如果您要检查用户是否登录,则此行代码将得到你想要的东西:

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

如果loggedIn为true,则不要进入登录页面

if loggedIn is true then don't go to login page

如果您想监听用户的身份验证状态,只需在AppDeledate中的firebase配置后添加一个auth状态监听器,如下所示:

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

顺便说一句,当您希望在身份验证状态更改时重新呈现某些屏幕时,此身份验证状态侦听器非常有用.您可以使用NotificationCenter.default.post(...)在上面的代码中发布通知,并在视图控制器中接收通知

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

这篇关于Firebase和Swift 4的持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆