Page Summary
-
To access Google services APIs like Drive and Gmail, apps need user consent and access tokens, typically obtained through OAuth 2.0 client flows, which the Google Sign-In library can implement for you.
-
Before making a Google API call, check the
grantedScopesproperty ofGIDGoogleUserto see which permissions your app already has. -
If your app needs additional permissions for a specific interaction, use
addScopes:presentingViewController:completionoraddScopes:presentingWindow:completionto request them from the user. -
To ensure your Google API calls use valid access tokens, wrap them in a
refreshTokensIfNeededWithCompletion:block to handle token expiration and renewal. -
You can use the refreshed access token by including it in the header of a REST or gRPC request or by utilizing the fetcher authorizer with the Google APIs Client Library.
Some Google services, such as Drive, Gmail, and many others, provide public APIs that you can use to create apps that help users work with their data in these services. To access these services, apps must implement one of the OAuth 2.0 client flows to get consent from users and obtain access tokens, which grant access to the APIs.
You can use the Google Sign-In library, which implements the OAuth 2.0 flow for you, to get access tokens for the signed-in user.
Prerequisites
Before your iOS app can call Google APIs, complete the following setup steps:
1. Enable APIs for your project
Any application that calls Google APIs needs to enable those APIs in the Google Cloud console.
To enable an API for your project:
- Open the API Library in the Google Cloud console.
- If prompted, select a project or create a new one.
- Select the API you want to enable, then click Enable.
2. Create authorization credentials
Any iOS application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to the Google authorization server. The following steps explain how to create credentials for your project:
- Go to the Credentials page in the Google Cloud console.
- Click Create client (or Create Credentials > OAuth client ID).
- Select the iOS application type.
- Enter a name for the OAuth client. This name identifies the client in your project's Credentials page.
- Enter the bundle identifier for your app. The bundle ID is the value of
the
CFBundleIdentifierkey in your app'sInfo.plist. The value is commonly displayed in the General pane or the Signing & Capabilities pane of the Xcode project editor, or in the App Information page on Apple App Store Connect. Confirm that you use the correct bundle ID, as it cannot be changed if you use App Check. - (Optional) Enter your app's App Store ID if the app is published in the Apple App Store. The Store ID is a numeric string included in every Apple App Store URL.
- (Optional) Enter your Team ID. See Locate your Team ID in the Apple Developer Account documentation. The Team ID is required if you enable App Check for your client.
- (Optional) Enable App Check for your iOS app. When you enable App Check, Apple's App Attest service is used to verify that OAuth 2.0 requests originating from your OAuth client are genuine and come from your app, helping to reduce the risk of app impersonation.
- Click Create.
Your client ID is generated and displayed in the Google Cloud console. Add the
reversed client ID URL scheme (for example,
com.googleusercontent.apps.1234567890-abcdef) to your app's Info.plist to
handle authorization redirects.
3. Complete basic Google Sign-In integration
Complete the basic Google Sign-In integration before requesting incremental scopes and calling Google APIs.
1. Check which scopes have been granted
Before you make a call to a Google API, check which scopes have already been
granted to your app, using the grantedScopes property of GIDGoogleUser:
Swift
let driveScope = "https://www.googleapis.com/auth/drive.readonly"
let grantedScopes = user.grantedScopes
if grantedScopes == nil || !grantedScopes!.contains(driveScope) {
// Request additional Drive scope.
}
Objective-C
NSString *driveScope = @"https://www.googleapis.com/auth/drive.readonly";
// Check if the user has granted the Drive scope
if (![user.grantedScopes containsObject:driveScope]) {
// request additional drive scope
}
Based on whether or not a certain scope has been granted by the user, you might need to make a request for an additional scope in order to support a particular interaction.
2. Request additional scopes
If you need to request additional scopes, call
addScopes:presentingViewController:completion or
addScopes:presentingWindow:completion to ask the user to grant your app
additional access.
For example, to request read-only access to a user's Drive files:
Swift
let additionalScopes = ["https://www.googleapis.com/auth/drive.readonly"]
guard let currentUser = GIDSignIn.sharedInstance.currentUser else {
return ; /* Not signed in. */
}
currentUser.addScopes(additionalScopes, presenting: self) { signInResult, error in
guard error == nil else { return }
guard let signInResult = signInResult else { return }
// Check if the user granted access to the scopes you requested.
}
Objective-C
NSArray *additionalScopes = @[ @"https://www.googleapis.com/auth/drive.readonly" ];
GIDGoogleUser *currentUser = GIDSignIn.sharedInstance.currentUser;
[currentUser addScopes:additionalScopes
presentingViewController:self
completion:^(GIDSignInResult * _Nullable signInResult,
NSError * _Nullable error) {
if (error) { return; }
if (signInResult == nil) { return; }
// Check if the user granted access to the scopes you requested.
}];
3. Make an API call with fresh tokens
To ensure that your Google API calls always have unexpired access tokens
attached, wrap the calls in a refreshTokensIfNeededWithCompletion: block:
Swift
currentUser.refreshTokensIfNeeded { user, error in
guard error == nil else { return }
guard let user = user else { return }
// Get the access token to attach it to a REST or gRPC request.
let accessToken = user.accessToken.tokenString
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
let authorizer = user.fetcherAuthorizer()
}
Objective-C
[currentUser refreshTokensIfNeededWithCompletion:^(
GIDGoogleUser * _Nullable user,
NSError * _Nullable error) {
if (error) { return; }
if (user == nil) { return; }
// Get the access token to attach it to a REST or gRPC request.
NSString *accessToken = user.accessToken.tokenString;
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
id<GTMFetcherAuthorizationProtocol> authorizer = [user fetcherAuthorizer];
}];
Use the access token to call the API, by either including the access token in
the header of a REST or gRPC request
(Authorization: Bearer ACCESS_TOKEN), or by using the
fetcher authorizer with the Google APIs Client Library.