简体   繁体   English

如何在 Swift 中使用 Firebase 保持用户登录?

[英]How to keep user logged in using Firebase in Swift?

I'm kinda new to Swift programming and I can't find any tutorial on how to keep users logged in after closing the app.我是 Swift 编程的新手,我找不到任何关于如何在关闭应用程序后让用户保持登录状态的教程。

I already did log in and sign up functionality in my app, but what are my steps to keep users logged after closing the app?我已经在我的应用程序中登录并注册了功能,但是在关闭应用程序后我要采取哪些步骤来让用户保持登录状态?

By default, users are already kept logged into the Firebase after closing the app.默认情况下,用户在关闭应用程序后已保持登录到 Firebase。

You can add an auth state listener to see this in action.您可以添加一个 auth state 侦听器以查看实际效果。 If at app startup (after Firebase is configured), you listen for the authorization state, you'll see that the app gets notified that the user is logged in already, assuming they had a valid authorization state at the time the app was last closed.如果在应用程序启动时(配置 Firebase 之后),您监听授权 state,您将看到应用程序收到用户已登录的通知,假设他们在应用程序上次关闭时具有有效授权 state .

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

See documentation: https://firebase.google.com/docs/auth/ios/start#listen_for_authentication_state请参阅文档: https://firebase.google.com/docs/auth/ios/start#listen_for_authentication_state

You can also use Userdefault to persist login state, such that upon successful login, you would persist a value lets call it isLoggedIn which is of type Bool and then all you need to do is to check for isLoggedIn upon each launch of your app, if true, then user is loggedin, you show your landing page otherwise you show your login screen.您还可以使用 Userdefault 来保留登录 state,这样在成功登录后,您将保留一个值,我们称之为 isLoggedIn,它是 Bool 类型,然后您需要做的就是在每次启动应用程序时检查 isLoggedIn,如果true,然后用户登录,你显示你的登陆页面,否则你显示你的登录屏幕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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