自动登录用户-Swift Firebase [英] log in user automatically - Swift Firebase

查看:56
本文介绍了自动登录用户-Swift Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个viewControllers的应用程序,第一个用于登录,第二个是tableViewController,它是该应用程序的主viewController.我试图在关闭应用程序并导航到主viewController后自动保持用户登录.我尝试了这段代码,它来自Firebase文档,但是当我启动该应用程序时,它显示致命错误:在展开一个Optional值时意外地找到了nil.

i have an application that have two viewControllers, the first one is for the login and the second one is a tableViewController and it is the main viewController for the application. Im trying to keep the user login automatically after closing the application and navigate to the main viewController. i tried this code and it is from firebase documentation but when i start the application it shows Fatal error: Unexpectedly found nil while unwrapping an Optional value.

这是我的AppDelegate代码:

this is my code for the AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate {
var db: Firestore!
var firebaseToken: String = ""
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    
    FirebaseApp.configure()
    
    self.registerForFirebaseNotification(application: application)
    Messaging.messaging().delegate = self
    
    

    handle = Auth.auth().addStateDidChangeListener { (auth, user) in
        if user != nil {
         
            
            let main = UIStoryboard(name: "Main", bundle: nil)
                   let vc = main.instantiateViewController(identifier: "viewController") as! ViewController
                   self.window?.rootViewController = vc
                   window?.makeKeyAndVisible()
            
        } else {
            // ...
        }
    }



    return true
    
}
    

推荐答案

Firebase身份验证在用户登录时自动将其存储到磁盘.重新启动应用程序时,Firebase会自动从这些凭据恢复用户的状态.但是此过程需要调用服务器(例如,检查帐户是否已禁用),这意味着在您的 Auth.auth().currentUser!= nil 运行该调用时可能尚未完成,当前用户 为零.

Firebase Authentication automatically stores the user credentials to disk when they sign in. When you restart the app, Firebase automatically restores the user's state from those credentials. But this process requires a call to the server (for example, to check if the account has been disabled), which means that by the time your Auth.auth().currentUser != nil runs that call probably hasn't yet completed and the current user is nil.

解决方案是使用auth状态侦听器,如

The solution is to use an auth state listener as shown in the first code snippet in the documentation on determining the current user.

Auth.auth().addStateDidChangeListener { (auth, user) in
    if user != nil {
        // ...
    } else {
        // ...
    }
}

这篇关于自动登录用户-Swift Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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