首页 > 解决方案 > Firebase User Auth check in App delegate

问题描述

I have implemented Firebase Auth and Firebase Database in app delegate which checks if the user is logged in or not.It checks in a 'users' node in Database to see if there is an userid in child snapshots or not and this operation takes about 2-3 seconds.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()

    if let uid = Auth.auth().currentUser?.uid {
        Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { snapshot in
            if snapshot.exists() {
                print("App Delegate: User found!")
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc  = storyboard.instantiateViewController(withIdentifier: "Main")
                self.window?.rootViewController = vc
                self.window?.makeKeyAndVisible()
            }
            else{
                print("App Delegate: User not found!")
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc  = storyboard.instantiateViewController(withIdentifier: "Login")
                self.window?.rootViewController = vc
                self.window?.makeKeyAndVisible()
        }
        })
    }
    return true
}

The Login viewController is the Initial viewController. When launch screen fades out, the login viewController is show and if the user is logged in, the Main viewController is shown but in this case, there is a time interval of 2-3 secs for which the Login viewController is being shown. I tried to implement NavigationController too but same problem.

So how can I not show Login viewController if the user is logged in and go straight to the Main viewController and manage that 2-3 time seconds of time interval effectively.

标签: iosswiftfirebasefirebase-realtime-databasefirebase-authentication

解决方案


在本地会话中跟踪 isLogin 变量使其在登录和注销成功时为真和假。当第一次登录时,然后检查您的会话变量 isLogin。您可以将会话保存在 UserDefault 或 Keychain 中。这样你就可以避免你的问题。

或者你只需​​要这样检查:

if FIRAuth.auth().currentUser != nil {
   presentHome()
} else {
 //User Not logged in
}

之后,当您导航到所需的 viewController 时,请在那里完成其余的事情。


推荐阅读