在 iOS 應用程式中存取 Google API

部分 Google 服務 (例如雲端硬碟、Gmail 等) 提供公開 API,可讓您建立應用程式,協助使用者在這些服務中處理資料。如要存取這些服務,應用程式必須實作其中一種 OAuth 2.0 用戶端流程,取得使用者同意並取得存取權杖,才能存取 API。

您可以使用 Google 登入程式庫,為您實作 OAuth 2.0 流程,取得已登入使用者的存取權杖。

必要條件

iOS 應用程式必須先完成下列設定步驟,才能呼叫 Google API:

1. 為專案啟用 API

任何呼叫 Google API 的應用程式,都必須在 Google Cloud 控制台中啟用這些 API。

如要為專案啟用 API,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中開啟 API 程式庫。
  2. 按照系統說明選取專案,或建立新專案。
  3. 選取要啟用的 API,然後點選「啟用」。

2. 建立授權憑證

任何使用 OAuth 2.0 存取 Google API 的 iOS 應用程式,都必須具備授權憑證,以便向 Google 授權伺服器識別應用程式。以下步驟說明如何為專案建立憑證:

  1. 前往 Google Cloud 控制台的「Credentials」(憑證) 頁面。
  2. 依序點選「建立用戶端」 (或「建立憑證」>「OAuth 用戶端 ID」)。
  3. 選取「iOS」iOS應用程式類型。
  4. 輸入 OAuth 用戶端名稱。這個名稱會在專案的「Credentials」(憑證) 頁面中識別用戶端。
  5. 輸入應用程式的軟體包 ID。軟體包 ID 是應用程式 Info.plist 中 CFBundleIdentifier 鍵的值。這個值通常會顯示在 Xcode 專案編輯器的「General」窗格或「Signing & Capabilities」窗格中,或 Apple App Store Connect 的「App Information」頁面中。請確認您使用的軟體包 ID 正確無誤,因為使用 App Check 後就無法變更。
  6. (選用) 如果應用程式已在 Apple App Store 發布,請輸入應用程式的 App Store ID。商店 ID 是每個 Apple App Store 網址中包含的數字字串。
  7. (選用) 輸入團隊 ID。請參閱 Apple 開發人員帳戶說明文件中的「找出團隊 ID」一節。如要為用戶端啟用 App Check,就必須提供團隊 ID。
  8. (選用) 為 iOS 應用程式啟用 App Check。啟用 App Check 後,系統會使用 Apple 的 App Attest 服務,驗證源自 OAuth 用戶端的 OAuth 2.0 要求是否為真,且來自您的應用程式,有助於降低應用程式遭冒用的風險。
  9. 點選「建立」。

系統會產生用戶端 ID,並顯示在 Google Cloud 控制台中。將反向用戶端 ID 網址配置 (例如 com.googleusercontent.apps.1234567890-abcdef) 新增至應用程式的 Info.plist,以處理授權重新導向。

3. 完成基本的 Google 登入整合

請先完成基本 Google 登入整合,再要求遞增範圍並呼叫 Google API。

1. 查看已授予的範圍

呼叫 Google API 前,請使用 GIDGoogleUser 的 grantedScopes 屬性,檢查應用程式已取得哪些範圍:

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 用戶端程式庫。