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

ドライブ、Gmail など、多くの Google サービスには、ユーザーがこれらのサービスでデータを操作するのに役立つアプリを作成するために使用できる公開 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 APIs クライアント ライブラリでフェッチャー認証子を使用します。