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, configure your Xcode project, and set your client ID](https://developers.google.com/identity/sign-in/ios/start-integrating).

[Try our iOS and macOS sample app to see how Sign-In works](https://developers.google.com/identity/sign-in/ios/sample-app).

## 1. Handle the authentication redirect URL

After a user authenticates with Google, the authentication flow redirects back
to your app with a URL containing the authentication response, including the
user's ID token. Passing this URL to `GIDSignIn` allows the SDK to parse the
response and return the user's credentials to your app.

### 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
`GIDSignIn`s `handleURL`:

### Swift

    @main
    struct MyApp: App {

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

## 2. 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 restorePreviousSignInWithCompletion:^(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`
              }
            }
        }
      }
    }

## 3. 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 adhering to the
[Google branding guidelines](https://developers.google.com/identity/branding-guidelines).

### Using SwiftUI

1. Make sure that you have added the [dependency for the SwiftUI "Sign in with Google" button](https://developers.google.com/identity/sign-in/ios/start-integrating#install_the_google_sign-in_dependencies_in_your_project)
   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 `UIApplication` extension to retrieve the active root view
   controller for presentation:

       extension UIApplication {
         // Minimal implementation to retrieve the active root view
         // controller for presentation. Apps presenting sign-in from deeper
         // within an existing view hierarchy should ensure they select the
         // appropriate view controller.
         var rootViewController: UIViewController? {
           let windowScene = connectedScenes
             .compactMap { scene in scene as? UIWindowScene }
             .first { scene in scene.activationState == .foregroundActive }
           return windowScene?.windows.first(where: { window in window.isKeyWindow })?.rootViewController
         }
       }

4. 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)

5. Trigger the sign in process when the button is pressed by adding a call to
   `GIDSignIn`'s
   `signIn(withPresenting:completion:)` method in
   your action:

       func handleSignInButton() {
         guard let rootViewController = UIApplication.shared.rootViewController else {
           // Handle error
           return
         }

         GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController) { signInResult, error in
           guard let result = signInResult 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](https://github.com/google/GoogleSignIn-iOS/blob/main/GoogleSignInSwift/Sources/GoogleSignInButtonViewModel.swift)
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
   `signIn:`. For example, use an `IBAction`:

   ### Swift

       @IBAction func signIn(sender: Any) {
         GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, 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
             signInWithPresentingViewController:self
                                     completion:^(GIDSignInResult * _Nullable signInResult,
                                                  NSError * _Nullable error) {
           if (error) {
             return;
           }

           // If sign in succeeded, display the app's main content View.
         }];
       }

## 4. Add a sign-out button

Add a sign-out button to your app, visible to signed-in users, that calls
`GIDSignIn`'s `signOut` method.

Calling `signOut` clears the sign-in state stored in `GIDSignIn` and
removes the user's credentials for your app from the Keychain. Your app is
responsible for updating its own state and UI. Signing out only applies to your
app. It does not sign the user out of other apps or services, and it does not
revoke the permissions the user granted to your app.

### Using SwiftUI

In SwiftUI, add a `Button` that calls `GIDSignIn.sharedInstance.signOut()`:

    Button("Sign Out") {
      GIDSignIn.sharedInstance.signOut()
      // Calling signOut() may not automatically trigger UI updates.
      // Update your app's state as needed.
    }

### Using UIKit

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:

- [Get users' Google Account profile information](https://developers.google.com/identity/sign-in/ios/people).
- [Authenticate with your backend](https://developers.google.com/identity/sign-in/ios/backend-auth) using the user's Google ID token.
- [Call Google APIs](https://developers.google.com/identity/sign-in/ios/api-access) on the user's behalf.