iOS アプリで Google API にアクセスする

ドライブ、Gmail などの一部の Google サービスでは、こうしたサービスでユーザーがデータを操作できるアプリを作成するための公開 API を提供しています。これらのサービスにアクセスするには、OAuth 2.0 クライアント フローのいずれかを実装して、ユーザーから同意を得るとともに、API へのアクセス権を付与するアクセス トークンを取得する必要があります。

Google ログイン ライブラリを使用して OAuth 2.0 フローを実装し、ログインしたユーザーのアクセス トークンを取得できます。

始める前に

基本的な Google ログインの統合を完了する必要があります。

1. 付与されているスコープを確認する

Google API を呼び出す前に、GIDGoogleUsergrantedScopes プロパティを使用して、アプリにすでに付与されているスコープを確認します。

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
}

ユーザーが特定のスコープを付与したかどうかに応じて、特定の操作をサポートするため、追加のスコープのリクエストが必要になることがあります。

2. 追加のスコープをリクエストする

追加のスコープをリクエストする必要がある場合は、addScopes:presentingViewController:completion または addScopes:presentingWindow:completion を呼び出して、アプリに追加のアクセス権を付与するようユーザーに求めます。

たとえば、ユーザーのドライブ ファイルに対する読み取り専用権限をリクエストするには、次のようにします。

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.新しいトークンを使用して API 呼び出しを行う

期限切れでないアクセス トークンが Google API 呼び出しに付加されるようにするには、それらの呼び出しを refreshTokensIfNeededWithCompletion: ブロックでラップします。

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];
}];

アクセス トークンを使用して API を呼び出すには、アクセス トークンを REST または gRPC リクエストのヘッダーに含めるか(Authorization: Bearer ACCESS_TOKEN)、またはフェッチャー承認ツールを使用してGoogle API クライアント ライブラリを使用します。