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

查看:82
本文介绍了退出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,email,token等...)。我注意到的问题是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天全站免登陆