Swift + GIDSignIn - hasAuthInKeyChain returns true but currentUser is still nil after calling signInSilently

时间:2017-03-22 18:44:17

标签: ios swift authentication keychain google-signin

I'm attempting to integrate Google sign-in into my app. Right now, I'm able to successfully log in a user with a Google account and the app works as expected - I'm able to access currentUser, get some information from it, and fill my app's views with the information. The problem is that when I relaunch the app, I'm unable to get a GIDGoogleUser even after calling signInSilently. hasAuthInKeychain returns true, so I know that an auth token must exist in the keychain. I just can't figure out why currentUser still returns nil after signing a user back into the app. The code I've written is below:

    guard let signIn = GIDSignIn.sharedInstance() else { fatalError() }
    signIn.scopes = ["https://www.googleapis.com/auth/plus.stream.read", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.login"]
    signIn.clientID = FIRApp.defaultApp()?.options.clientID
    signIn.delegate = self
    if signIn.hasAuthInKeychain() {
        signIn.signInSilently()
    }

    if signIn.hasAuthInKeychain() || FBSDKAccessToken.current() != nil {

        var token = String()
        if let user = signIn.currentUser{
            token = user.userID
        } else{
            token = FBSDKAccessToken.current().userID
        }
    }

The app tries to sign in silently since hasAuthInKeychain returns true. But it skips past the if let statement because currentUser is nil and goes directly into trying to find a FBSDKAccessToken. I've tried all the suggestions I've found including setting the sign-in scopes. Am I missing something?

1 个答案:

答案 0 :(得分:2)

我有类似的问题。首先我认为这是一个时间问题。通过在完全加载根viewController之后调用signIn.signInSilently(),它确实有效。我现在99%肯定通过在主线程上执行signIn.signInSilently()来解决它:

DispatchQueue.main.async {
    gidSignIn.signInSilently()
}