UserDefaults 自动登录问题

UserDefaults Auto-Login trouble

我已尽一切可能让用户通过 UserDefaults 保持登录状态。但是,每次我登录、关闭应用程序并再次打开时,应用程序都会恢复到登录屏幕。我尝试使用其他类似问题的解决方案,但 none 有效。

下面是点击“登录”按钮时我的登录屏幕中的一些代码:

@IBAction func logInTapped(_ sender: Any) {
    let email = firstNameTF.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let password = lastNameTF.text!.trimmingCharacters(in: .whitespacesAndNewlines)

    
    Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        if error != nil{
            //couldnt sign in
            self.errorLabel.text = error!.localizedDescription
            self.errorLabel.alpha = 1
        } else {
            if #available(iOS 13.0, *) {
                self.errorLabel.text = "Logged in"
                self.errorLabel.isHidden = false
                print("log in successful")
                self.userDefaults.setValue(true, forKey: "user_uid_key")
                self.userDefaults.synchronize()
                self.transitionToHome()

            } else {
            }
        }
    }
           
}

最后,这是来自我的 AppDelegate 的代码:

var window: UIWindow?
let userDefaults = UserDefaults.standard

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


    
    FirebaseApp.configure()
        check()
    window = UIWindow()
    window?.makeKeyAndVisible()

// window?.rootViewController = UINavigationController(rootViewController: SViewController())

    return true
}
    func check() {
        if userDefaults.value(forKey: "user_uid_key") as? Bool == true {

            
            self.window = UIWindow(frame: UIScreen.main.bounds)

Link 到调试项目的 zip 文件:https://drive.google.com/file/d/1Hd-E4yaHN70nH2wj0l9rP6xDLUC9oHEA/view?usp=sharing

新场景代理:

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let windowScene = (scene as? UIWindowScene) else { return }
    
    if userDefaults.value(forKey: "user_uid_key") as? Bool == true {
        print("userdefaults function is running")
        

        self.window = UIWindow(windowScene: windowScene)
  //                        self.window = UIWindow(windowScene: UIScreen.main.bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "TBCID") as! UITabBarController

        self.window?.rootViewController = initialViewController

        self.window?.makeKeyAndVisible()


    }
}

这里的问题是 UIWindow(frame:) 没有按预期工作,从 iOS 13 开始,您需要将逻辑移至 SceneDelegate.swiftUIWindow(windowScene:)。另请查看缩进和右括号。

旧答案:

假设 check() 中的第一个 if 评估为 true 你正在做 self.window?.rootViewController = initialViewControllerself.window?.makeKeyAndVisible() 但是当 check() 完成时你是创建一个新的 UIWindow 并在这个新的 UIWindow 上做 window?.makeKeyAndVisible()

我认为你想做的是(尽量保持你的风格):

var window: UIWindow?
let userDefaults = UserDefaults.standard

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()
        
    check()

    return true
}

func check() -> Bool {
    if userDefaults.value(forKey: "user_uid_key") as? Bool == true {
   
        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "TBCID") as! TBCVC

        self.window?.rootViewController = initialViewController

        self.window?.makeKeyAndVisible()

    } else {

        window = UIWindow()

        window?.rootViewController = UINavigationController(rootViewController: SViewController())

        window?.makeKeyAndVisible()
    }
}