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

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

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

始める前に

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 クライアント ライブラリでフェッチャー承認機能を使用します。