Authenticate Using Google Sign-In on iOS

You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app.

Before you begin

  1. Add Firebase to your iOS project. Include the following pods in your Podfile:
    pod 'Firebase/Auth'
    pod 'GoogleSignIn'
    
  2. If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
  3. Enable Google Sign-In in the Firebase console:
    1. In the Firebase console, open the Auth section.
    2. On the Sign in method tab, enable the Google sign-in method and click Save.

1. Import the required header files

First, you must import the Firebase SDK and Google Sign-In SDK header files into your app.

Objective-C

In your app delegate, import the following header files:

@import Firebase;

#import <GoogleSignIn/GoogleSignIn.h>

In the view controller of your sign-in view, import the following header files:

@import Firebase;

#import <GoogleSignIn/GoogleSignIn.h>

Swift

In your app delegate, import the following header files:

import Firebase

In the view controller of your sign-in view, import the following header files:

import Firebase

In your app's project-Bridging-Header.h file, add the following:

#import <GoogleSignIn/GoogleSignIn.h>

If your project does not have a project-Bridging-Header.h file, you can create one by adding an Objective-C file to your app. The easiest way to do this is to drag and drop a .m file into your project—which creates the bridging header and configures your project to use it—then delete the .m file. See Swift and Objective-C in the Same Project.

2. Implement Google Sign-In

Implement Google Sign-In by following these steps. See the Google Sign-In developer documentation for details on using Google Sign-In with iOS.

  1. Add custom URL schemes to your Xcode project:
    1. Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.
    2. Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the GoogleService-Info.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.

      When completed, your config should look something similar to the following (but with your application-specific values):

  2. Declare that the app delegate implements the GIDSignInDelegate protocol.

    Objective-C

    In AppDelegate.h:
    @interface AppDelegate : UIResponder <UIApplicationDelegate, GIDSignInDelegate>
    

    Swift

    In AppDelegate.swift:
    class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
      // ...
    
  3. In your app delegate's application:didFinishLaunchingWithOptions: method, configure the FIRApp object and set the sign-in delegate.

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
    [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
    [GIDSignIn sharedInstance].delegate = self;
    

    Swift

    // Use Firebase library to configure APIs
    FIRApp.configure()
    
    GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    
  4. Implement the application:openURL:options: method of your app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.

    Objective-C

    - (BOOL)application:(UIApplication *)app
                openURL:(NSURL *)url
                options:(NSDictionary<NSString *, id> *)options {
      return [[GIDSignIn sharedInstance] handleURL:url
                                 sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                        annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
    }
    

    Swift

    func application(application: UIApplication,
      openURL url: NSURL, options: [String: AnyObject]) -> Bool {
        return GIDSignIn.sharedInstance().handleURL(url,
            sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
            annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
    }
    

    For your app to run on iOS 8 and older, also implement the deprecated application:openURL:sourceApplication:annotation: method.

    Objective-C

    - (BOOL)application:(UIApplication *)application
                openURL:(NSURL *)url
      sourceApplication:(NSString *)sourceApplication
             annotation:(id)annotation {
      return [[GIDSignIn sharedInstance] handleURL:url
                                 sourceApplication:sourceApplication
                                        annotation:annotation];
    }
    

    Swift

    func application(application: UIApplication,
      openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
        var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication,
                                            UIApplicationOpenURLOptionsAnnotationKey: annotation]
        return GIDSignIn.sharedInstance().handleURL(url,
            sourceApplication: sourceApplication,
            annotation: annotation)
    }
    
  5. In the app delegate, implement the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods:

    Objective-C

    - (void)signIn:(GIDSignIn *)signIn
    didSignInForUser:(GIDGoogleUser *)user
         withError:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(@"%@", error.localizedDescription);
      }
    }
    
    - (void)signIn:(GIDSignIn *)signIn
    didDisconnectWithUser:(GIDGoogleUser *)user
         withError:(NSError *)error {
      // Perform any operations when the user disconnects from app here.
      // ...
    }
    

    Swift

    func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
      withError error: NSError!) {
        if let error = error {
          print(error.localizedDescription)
          return
        }
        // ...
    }
    
    func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
      withError error: NSError!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }
    
  6. Declare that your sign-in view's controller implements the GIDSignInUIDelegate protocol.

    Objective-C

    In the view controller's header file:

    @interface GoogleSignInViewController : UIViewController <GIDSignInUIDelegate>
    

    Swift

    In the view controller:

    class GoogleSignInViewController: UIViewController, GIDSignInUIDelegate {
      // ...
    
  7. In the view controller, override the viewDidLoad method to set the UI delegate of the GIDSignIn object, and (optionally) to sign in silently when possible.

    Objective-C

    - (void)viewDidLoad {
      [super viewDidLoad];
    
      // TODO(developer) Configure the sign-in button look/feel
    
      [GIDSignIn sharedInstance].uiDelegate = self;
    
      // Uncomment to automatically sign in the user.
      //[[GIDSignIn sharedInstance] signInSilently];
    }
    

    Swift

    override func viewDidLoad() {
      super.viewDidLoad()
    
      GIDSignIn.sharedInstance().uiDelegate = self
    
      // Uncomment to automatically sign in the user.
      //GIDSignIn.sharedInstance().signInSilently()
    
      // TODO(developer) Configure the sign-in button look/feel
      // ...
    }
    
  8. Add a GIDSignInButton to your storyboard, XIB file, or instantiate it programmatically. To add the button to your storyboard or XIB file, add a View and set its custom class to GIDSignInButton.
  9. Optional: If you want to customize the button, do the following:

    Objective-C

    1. In your view controller's header file, declare the sign-in button as a property.
      @property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    2. Connect the button to the signInButton property you just declared.
    3. Customize the button by setting the properties of the GIDSignInButton object.

    Swift

    1. In your view controller, declare the sign-in button as a property.
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. Connect the button to the signInButton property you just declared.
    3. Customize the button by setting the properties of the GIDSignInButton object.

3. Authenticate with Firebase

In the signIn:didSignInForUser:withError: method, get a Google ID token and Google access token from the GIDAuthentication object and exchange them for a Firebase credential:

Objective-C

- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
  if (error == nil) {
    GIDAuthentication *authentication = user.authentication;
    FIRAuthCredential *credential =
    [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
                                     accessToken:authentication.accessToken];
    // ...
  } else
    // ...
}

Swift

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

  let authentication = user.authentication
  let credential = FIRGoogleAuthProvider.credential(withIDToken: (authentication?.idToken)!,
      accessToken: (authentication?.accessToken)!)
  // ...
}

Finally, authenticate with Firebase using the credential:

Objective-C

[[FIRAuth auth] signInWithCredential:credential
                          completion:^(FIRUser *user, NSError *error) {
                            // ...
                          }];

Swift

FIRAuth.auth()?.signIn(with: credential) { (user, error) in
  // ...
}

Next steps

After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and password, or auth provider information—the user signed in with. This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.

  • In your apps, you can get the user's basic profile information from the FIRUser object. See Manage Users.

  • In your Firebase Realtime Database and Firebase Storage Security Rules, you can get the signed-in user's unique user ID from the auth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account.

To sign out a user, call signOut:.

Objective-C

NSError *error;
[[FIRAuth auth] signOut:&error;];
if (!error) {
  // Sign-out succeeded
}

Swift

try! FIRAuth.auth()!.signOut()

You may also want to add error handling code for the full range of authentication errors. See Handle Errors.

Send feedback about...

Need help? Visit our support page.