部分 Google 服務 (例如雲端硬碟、Gmail 等) 提供公開 API,您可以使用這些 API 建立應用程式,協助使用者處理這些服務中的資料。如要存取這些服務,應用程式必須實作其中一種 OAuth 2.0 用戶端流程,徵求使用者同意並取得存取權杖,才能存取 API。
您可以使用 Google 登入程式庫 (實作 OAuth 2.0 流程),為已登入的使用者取得存取權杖。
事前準備
您必須完成基本的 Google 登入整合。
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 用戶端程式庫使用擷取器授權人。