在 iOS 應用程式中存取 Google API

部分 Google 服務 (例如雲端硬碟、Gmail 等) 會提供公用 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:completionaddScopes: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 用戶端程式庫搭配使用。