在 Firebase 中退出应用程序后如何维护用户会话 [英] How to maintain user session after exiting app in Firebase

查看:23
本文介绍了在 Firebase 中退出应用程序后如何维护用户会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Firebase 作为后端的应用.我的应用使用简单的电子邮件和密码登录来实现 Firebase-Authentication API 进行身份验证.

I have an app using Firebase as backend. My App implements Firebase-Authentication API using simple Email and Password login for authenticating.

除了一个问题外,一切正常.即使在用户关闭应用程序后,我也希望保持用户会话.

Everything works fine except for one issue. I would like to maintain the user session even after a user closes the App.

FIRAuth.auth()?.currentUser?具有当前用户的所有用户属性(例如:uid、电子邮件、令牌等),效果很好.我注意到的问题是 FIRAuth.auth()?.currentUser?不持久.所以退出应用程序并再次启动后,它返回null.

FIRAuth.auth()?.currentUser? has all the user properties (ex: uid, email, token etc...) for the current user which works great. The problem I noticed is that FIRAuth.auth()?.currentUser? is not persistent. So after exiting the app and launching again, it returns null.

我不想在用户每次打开应用程序时都要求再次登录.有没有办法解决这个问题?

I would not like to ask a user every time they open the app to login again. Is there a way around this?

推荐答案

Firebase 应该已经通过应用启动跟踪您的用户.

Firebase should already be keeping track of your user through app launches.

您的问题可能是直接使用 FIRAuth.auth()?.currentUser? 而不是推荐的方法.

Your issue could be with using FIRAuth.auth()?.currentUser? directly rather than the recommended approach.

获取当前用户的推荐方式是设置监听器在 Auth 对象上:

The recommended way to get the current user is by setting a listener on the Auth object:

FIRAuth.auth()?.addStateDidChangeListener { auth, user in
  if let user = user {
    // User is signed in.
  } else {
    // No user is signed in.
  }
}

通过使用侦听器,您可以确保 Auth 对象不在中间状态——比如初始化——当你得到当前用户.

By using a listener, you ensure that the Auth object isn't in an intermediate state—such as initialisation—when you get the current user.

在我自己的应用程序中,我同时使用两者.如果使用第一种方法的用户不存在,则转到第二种方法,如果失败,则显示登录/注册屏幕.

In my own application, I use both. If the user doesn't exist with the first method, it moves onto the second, and if that fails, present login/signup screen.

这篇关于在 Firebase 中退出应用程序后如何维护用户会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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