如何保持用户使用Google登录名登录?

时间:2019-04-01 18:45:10

标签: ios swift firebase google-signin

我正在尝试让用户退出应用程序后保持登录状态。当用户按下主页按钮然后再次返回时,它确实使他们保持登录状态(并从我正在使用的Google Classroom API中加载数据)。但是,当用户强制关闭应用程序时,它不会关闭。我想让用户在强制关闭应用程序后保持登录状态(就像按下主屏幕按钮时一样)。有没有办法做到这一点?我正在使用Google Signin&Firebase登录。

我在这里登录用户:

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
    // ...
    if let error = error {
        // ...
        return
    }

    print("User Signed into Google")

    guard let authentication = user.authentication else { return }

    // Set the OAuth authorizer for the Classroom API
    service.authorizer = authentication.fetcherAuthorizer()

    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    // ...
    Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
        if let error = error {
            // ...
            return
        }
        // User is signed in
        print("User is Signed into Firebase using Google Sign In")

        //let welcomeScreen = WelcomeScreenViewController()

        //welcomeScreen.performSegueToHomeworkScreen()
        if Auth.auth().currentUser != nil {
            let navigationController = self.window?.rootViewController as! UINavigationController
            for controller in navigationController.viewControllers {
                if let LoginViewController = controller as? LogInViewContoller {
                    LoginViewController.performSegue(withIdentifier: "logInToHome", sender: nil)
                    break
                }
            }

        }
    }
}

当用户打开应用程序时:

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    GIDSignIn.sharedInstance().signInSilently()

}

非常感谢您。

1 个答案:

答案 0 :(得分:1)

即使强制退出应用程序,当前Firebase用户仍保持登录状态。由于代码正在调用GIDSignIn.sharedInstance().signInSilently(),因此该操作会将用户登录到其Google帐户,但不会自动将其登录到Firebase。不用使用它,而是添加一个state change listener

handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  if user == nil {
    // prompt user to sign in
  } else {
    // you know the current user
  }
}

此功能关闭将在每次对身份验证进行更改时运行,因此,如果用户随后注销,则将再次触发此操作,您将看到不再有用户登录并可以进行相应处理。当用户登录时,关闭将再次运行,您可以对用户进行所需的操作。