Integrating Google Sign-In into your iOS or macOS app

Stay organized with collections Save and categorize content based on your preferences.

This page shows you how to integrate Google Sign-In into an iOS or macOS app. You may need to adapt these instructions for your app's lifecycle or UI model.

Before you begin

Download the dependencies and configure your Xcode project.

1. Configure the Google Sign-In library

Create a GIDConfiguration object using the client IDs you created while completing the getting started steps. You can do this wherever you keep app configuration state, such as a singleton object.

Swift

let signInConfig = GIDConfiguration(clientID: "YOUR_IOS_CLIENT_ID")

Objective-C

signInConfig = [[GIDConfiguration alloc] initWithClientID:@"YOUR_IOS_CLIENT_ID"];

If you need to get users' ID tokens for backend authentication, also set the serverClientID parameter. If you want to optimize the sign-in flow for a Google Workspace domain, or if you want to specify an OpenID realm, you can use the hostedDomain and openIDRealm parameters, respectively.

2. Handle the authentication redirect URL

iOS: UIApplicationDelegate

In your AppDelegate’s application:openURL:options method, call GIDSignIn's handleURL: method:

Swift

func application(
  _ app: UIApplication,
  open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
  var handled: Bool

  handled = GIDSignIn.sharedInstance.handle(url)
  if handled {
    return true
  }

  // Handle other custom URL types.

  // If not handled by this app, return false.
  return false
}

Objective-C

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  BOOL handled;

  handled = [GIDSignIn.sharedInstance handleURL:url];
  if (handled) {
    return YES;
  }

  // Handle other custom URL types.

  // If not handled by this app, return NO.
  return NO;
}

macOS: NSApplicationDelegate

  1. In your app's AppDelegate register a handler for kAEGetURL events in applicationDidFinishLaunching:

    Swift

    func applicationDidFinishLaunching(_ notification: Notification) {
      // Register for GetURL events.
      let appleEventManager = NSAppleEventManager.shared()
      appleEventManager.setEventHandler(
        self,
        andSelector: "handleGetURLEvent:replyEvent:",
        forEventClass: AEEventClass(kInternetEventClass),
        andEventID: AEEventID(kAEGetURL)
      )
    }
    

    Objective-C

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
      // Register for GetURL events.
      NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
      [appleEventManager setEventHandler:self
                         andSelector:@selector(handleGetURLEvent:withReplyEvent:)
                         forEventClass:kInternetEventClass
                         andEventID:kAEGetURL];
    }
    
  2. Define the handler for these events that calls GIDSignIn's handleURL:

    Swift

    func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
        if let urlString =
          event?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue{
            let url = NSURL(string: urlString)
            GIDSignIn.sharedInstance.handle(url)
        }
    }
    

    Objective-C

    - (void)handleGetURLEvent:(NSAppleEventDescriptor *)event
         withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
          NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
          NSURL *URL = [NSURL URLWithString:URLString];
          [GIDSignIn.sharedInstance handleURL:url];
    }
    

SwiftUI

In your app's window or scene, register a handler to receive the URL and call GIDSignIns handleURL:

Swift

@main
struct MyApp: App {

  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onOpenURL { url in
          GIDSignIn.sharedInstance.handle(url)
        }
    }
  }
}

3. Attempt to restore the user's sign-in state

When your app starts up, call restorePreviousSignInWithCallback to try and restore the sign-in state of users who already signed in using Google. Doing so ensures users don't have to sign in every time they open your app (unless they've signed out).

iOS apps often do this in UIApplicationDelegate's application:didFinishLaunchingWithOptions: method and NSApplicationDelegate's applicationDidFinishLaunching: for macOS apps. Use the result to determine which view to present to the user. For example:

Swift

func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
  GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
    if error != nil || user == nil {
      // Show the app's signed-out state.
    } else {
      // Show the app's signed-in state.
    }
  }
  return true
}

Objective-C

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GIDSignIn.sharedInstance restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
                                                                NSError * _Nullable error) {
    if (error) {
      // Show the app's signed-out state.
    } else {
      // Show the app's signed-in state.
    }
  }];
  return YES;
}

SwiftUI

If you're using SwiftUI, add a call to restorePreviousSignIn in onAppear for your initial view:

Swift

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onAppear {
          GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
            // Check if `user` exists; otherwise, do something with `error`
          }
        }
    }
  }
}

4. Add a Google Sign-In button

Add a "Sign in with Google" button to your sign-in View. Components are available for SwiftUI and UIKit that automatically generate a button with Google branding and are recommended for use.

Using SwiftUI

  1. Make sure that you have added the dependency for the SwiftUI "Sign in with Google" button to your project.

  2. In the file where you want to add the SwiftUI button, add the required import to the top of the file:

    import GoogleSignInSwift
    
  3. Add a "Sign in with Google" button to your View and specify the action that will be called when the button is pressed:

    GoogleSignInButton(action: handleSignInButton)
    
  4. Trigger the sign in process when the button is pressed by adding a call to GIDSignIn's signIn(configuration:presentingViewController:callback:) method in your action:

    func handleSignInButton() {
      GIDSignIn.sharedInstance.signIn(
        with: signInConfig,
        presenting: presentingViewController) { user, error in
          guard let signInUser = user else {
            // Inspect error
            return
          }
          // If sign in succeeded, display the app's main content View.
        }
      )
    }
    

This uses the default view model that provides standard styling information for the button. To control the button's appearance, you need to create a custom GoogleSignInButtonViewModel and set it as the viewModel in the button's initializer using GoogleSignInButton(viewModel: yourViewModel, action: yourAction). See the GoogleSignInButtonViewModel source code for more information.

Using UIKit

  1. Add a "Sign in with Google" button to your sign-in View. You can use the GIDSignInButton class to automatically generate a button with Google branding (recommended) or create your own button with custom styling.

    To add a GIDSignInButton to a storyboard or XIB file, add a View and set its custom class to GIDSignInButton. Note that when you add a GIDSignInButton View to your storyboard, the sign-in button doesn't render in the interface builder. Run the app to see the sign-in button.

    You can customize the appearance of a GIDSignInButton by setting its colorScheme and style properties:

    GIDSignInButton style properties
    colorScheme kGIDSignInButtonColorSchemeLight
    kGIDSignInButtonColorSchemeDark
    style kGIDSignInButtonStyleStandard
    kGIDSignInButtonStyleWide
    kGIDSignInButtonStyleIconOnly
  2. Connect the button to a method in your ViewController that calls signInWithConfiguration:, passing the configuration object you created in step 1. For example, use an IBAction:

    Swift

    @IBAction func signIn(sender: Any) {
      GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
        guard error == nil else { return }
    
        // If sign in succeeded, display the app's main content View.
      }
    }
    

    Objective-C

    - (IBAction)signIn:(id)sender {
      [GIDSignIn.sharedInstance signInWithConfiguration:signInConfig
                               presentingViewController:self
                                               callback:^(GIDGoogleUser * _Nullable user,
                                                          NSError * _Nullable error) {
        if (error) {
          return;
        }
    
        // If sign in succeeded, display the app's main content View.
      }];
    }
    

5. Add a sign-out button

  1. Add a sign-out button to your app, visible to signed-in users.

  2. Connect the button to a method in your ViewController that calls signOut:. For example, use an IBAction:

    Swift

    @IBAction func signOut(sender: Any) {
      GIDSignIn.sharedInstance.signOut()
    }
    

    Objective-C

    - (IBAction)signOut:(id)sender {
      [GIDSignIn.sharedInstance signOut];
    }
    

Next steps

Now that users can sign in to your app using their Google Accounts, learn how to: