Search code examples
swiftxcodefirebasegoogle-oauthgidsignin

GIDSignIn current user is nil after restorePreviousSignIn()


My issue here is that: This shared instance is called

GIDSignIn.sharedInstance.restorePreviousSignIn()

But when I try to check the current user it remains nil after the call.

GIDSignIn.sharedInstance.currentUser != nil

I would assume I may need a proper delay before checking if the user is nil or not. How can I properly add a delay or populate the user before checking if the user is nil.

ex: confirming that GIDSignIn.sharedInstance.restorePreviousSignIn() has finished before checking GIDSignIn.sharedInstance.currentUser

 if(GIDSignIn.sharedInstance.hasPreviousSignIn() && GIDSignIn.sharedInstance.currentUser == nil) {
                GIDSignIn.sharedInstance.restorePreviousSignIn()    
        }else{
                print("user has no shared instance. User has not been prev signed in")
        }
        
        
        
        if (GIDSignIn.sharedInstance.currentUser != nil) {
         }else{
               print("user is nil")
        }

Using GoogleSignIn SDK GoogleSignIn Framework Reference


Solution

  • If you studied at the documentation you linked you'd be able to see the restorePreviousSiginin is asynchronous and also know how to use it.

    func restorePreviousSignIn(callback: GIDSignInCallback? = nil)

    callback
    The GIDSignInCallback block that is called on completion. This block will be called asynchronously on the main queue.

    where the completion handler is defined as:

    typealias GIDSignInCallback = (GIDGoogleUser?, Error?) -> Void

    You should use the completion handler to process the result of trying to restore the previous sign in, not try to do it synchronously in the method. Something like

    if(GIDSignIn.sharedInstance.hasPreviousSignIn() && GIDSignIn.sharedInstance.currentUser == nil) {
      GIDSignIn.sharedInstance.restorePreviousSignIn() { 
        user, error in
        if let user = user {
          print(user)  // handle the user info
        } else {
           print(error ?? "unknown error")
        }
      }
    }