如何通过Google登录保持用户登录?

问题描述 投票:1回答:1

我试图让用户在退出应用程序后登录。当用户按下主页按钮然后再次返回时,它会让他们保持登录状态(并从我正在使用的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()

}

非常感谢你。

ios swift firebase google-signin
1个回答
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
  }
}

每次更改身份验证时都会运行此函数关闭,因此如果用户随后注销,则会再次触发此操作,您将看到用户已经不再登录并可以相应地处理它。当用户登录时,将再次运行关闭,您可以执行用户需要执行的操作。

© www.soinside.com 2019 - 2024. All rights reserved.