首页 > 解决方案 > 如何在 Firebase iOS13+ 中保持登录状态

问题描述

这个问题已经在这里问过了,解决方案不再相关,因为iOS13有一些变化。关闭应用程序并重新打开后如何保持登录状态。

我有WelcomeViewController,未登录时出现的,以及CoffeeViewController: UIViewController用户登录时应该出现的类。

class CoffeeViewController: UIViewController {

override func viewDidLoad() {
        super.viewDidLoad()
        checkAuthn()
}

  func checkAuthn() {
             if Auth.auth().currentUser == nil {
                 DispatchQueue.main.async {
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    let initialViewController = storyboard.instantiateViewController(withIdentifier: "welcomeScreen") as? WelcomeViewController
                    self.present(initialViewController!, animated: true, completion: nil)
                 }
             } else {
            print("Done")
             }
         }

}

SceneDelegate我知道我应该在(以前是在didFinishLaunchingWithOptions方法中)实现 rootview 控制器。而且我不知道如何正确地制作它。我尝试过这种方式,但它对我不起作用。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
       let vc = CoffeeViewController()
       let nc = UINavigationController(rootViewController: vc)
        window?.rootViewController = nc
        window?.makeKeyAndVisible()
        
    }

- - - - - - - - - - - - -第2部分 - - - - - - - - - - - - ------------------

在sceneDelegate发生变化之后:

guard let windowsScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(windowScene: windowScene)
        window?.rootViewController = UINavigationController(rootViewController: CoffeeViewController())
        window?.makeKeyAndVisible()

我收到错误:

错误

-------------------------第 3 部分解决方案---------- ------------

我替换了 sceneDelegate 中的代码,它工作正常。

guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(windowScene: windowScene)
        let homeVC = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "ShopsMain") as! CoffeeViewController
        let navC = UINavigationController(rootViewController: homeVC)
        window?.rootViewController = navC
        window?.makeKeyAndVisible()

标签: swiftfirebaseloggingfirebase-authenticationios13

解决方案


您需要初始化windowin UISceneDelegate

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    window?.rootViewController = UINavigationController(rootViewController: CoffeeViewController())
    window?.makeKeyAndVisible()
}

推荐阅读