Page Summary
-
This page provides instructions for integrating Google Sign-In into iOS or macOS applications.
-
Key steps include handling authentication redirect URLs, restoring previous sign-in states, adding a Google Sign-In button, and adding a sign-out button.
-
The guide provides code examples for implementing these steps in Swift, Objective-C, and SwiftUI where applicable.
-
It is recommended to use the provided SwiftUI and UIKit components for adding the Google Sign-In button to ensure consistent branding.
-
Users can learn how to access profile information, authenticate with their backend, and call Google APIs after successful sign-in.
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.
Try our iOS and macOS sample app to see how Sign-In works.
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
In your app's AppDelegate register a handler for
kAEGetURLevents inapplicationDidFinishLaunching: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]; }Define the handler for these events that calls
GIDSignIn'shandleURL: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)
}
}
}
}
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.
Using SwiftUI
Make sure that you have added the dependency for the SwiftUI "Sign in with Google" button to your project.
In the file where you want to add the SwiftUI button, add the required import to the top of the file:
import GoogleSignInSwiftAdd a
UIApplicationextension 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 } }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)Trigger the sign in process when the button is pressed by adding a call to
GIDSignIn'ssignIn(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
for more information.
Using UIKit
Add a "Sign in with Google" button to your sign-in View. You can use the
GIDSignInButtonclass to automatically generate a button with Google branding (recommended) or create your own button with custom styling.To add a
GIDSignInButtonto a storyboard or XIB file, add a View and set its custom class toGIDSignInButton. Note that when you add aGIDSignInButtonView 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
GIDSignInButtonby setting itscolorSchemeandstyleproperties:GIDSignInButton style properties colorSchemekGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDarkstylekGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnlyConnect the button to a method in your ViewController that calls
signIn:. For example, use anIBAction: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.
- Authenticate with your backend using the user's Google ID token.
- Call Google APIs on the user's behalf.