Drive, Gmail 등 일부 Google 서비스는 사용자가 이러한 서비스에서 데이터를 사용하는 데 도움이 되는 앱을 만드는 데 사용할 수 있는 공개 API를 제공합니다. 이러한 서비스에 액세스하려면 앱에서 OAuth 2.0 클라이언트 흐름 중 하나를 구현하여 API에 대한 액세스 권한을 부여하는 액세스 토큰을 얻어야 합니다.
OAuth 2.0 흐름을 구현하는 Google 로그인 라이브러리를 사용하여 로그인한 사용자의 액세스 토큰을 가져올 수 있습니다.
시작하기 전에
기본 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
를 호출하여 사용자에게 앱에 추가 액세스 권한을 부여해 달라고 요청하세요.
예를 들어 사용자의 Drive 파일에 대한 읽기 전용 액세스 권한을 요청하려면 다음 안내를 따르세요.
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];
}];
액세스 토큰을 사용하여 REST 또는 gRPC 요청 헤더에 액세스 토큰을 포함하거나 (Authorization: Bearer ACCESS_TOKEN
) Google API 클라이언트 라이브러리와 함께 가져오기 승인자를 사용하여 API를 호출합니다.