Drive, Gmail 등 일부 Google 서비스는 사용자가 이러한 서비스에서 데이터를 사용하는 데 도움이 되는 앱을 만드는 데 사용할 수 있는 공개 API를 제공합니다. 이러한 서비스에 액세스하려면 앱에서 OAuth 2.0 클라이언트 흐름 중 하나를 구현하여 사용자로부터 동의를 얻고 API에 대한 액세스 권한을 부여하는 액세스 토큰을 가져와야 합니다.
OAuth 2.0 플로우를 구현하는 Google 로그인 라이브러리를 사용하여 로그인한 사용자의 액세스 토큰을 가져올 수 있습니다.
기본 요건
iOS 앱에서 Google API를 호출하려면 먼저 다음 설정 단계를 완료하세요.
1. 프로젝트에 API 사용 설정
Google API를 호출하는 모든 애플리케이션은 Google Cloud 콘솔에서 해당 API를 사용 설정해야 합니다.
프로젝트에 API를 사용 설정하려면 다음 단계를 따르세요.
- Google Cloud 콘솔에서 API 라이브러리를 엽니다.
- 메시지가 표시되면 프로젝트를 선택하거나 새로운 프로젝트를 만듭니다.
- 사용 설정하려는 API를 선택한 다음 사용 설정을 클릭합니다.
2. 승인 사용자 인증 정보 만들기
OAuth 2.0을 사용하여 Google API에 액세스하는 모든 iOS 애플리케이션에는 Google 승인 서버에 애플리케이션을 식별하는 승인 사용자 인증 정보가 있어야 합니다. 다음 단계에서는 프로젝트의 사용자 인증 정보를 만드는 방법을 설명합니다.
- Google Cloud 콘솔의 사용자 인증 정보 페이지로 이동합니다.
- 클라이언트 만들기 (또는 사용자 인증 정보 만들기 > OAuth 클라이언트 ID)를 클릭합니다.
- iOS 애플리케이션 유형을 선택합니다.
- OAuth 클라이언트의 이름을 입력합니다. 이 이름은 프로젝트의 사용자 인증 정보 페이지에서 클라이언트를 식별합니다.
- 앱의 번들 식별자를 입력합니다. 번들 ID는 앱의
Info.plist에 있는CFBundleIdentifier키의 값입니다. 이 값은 일반적으로 Xcode 프로젝트 편집기의 일반 창 또는 서명 및 기능 창이나 Apple App Store Connect의 앱 정보 페이지에 표시됩니다. 앱 체크를 사용하는 경우 번들 ID를 변경할 수 없으므로 올바른 번들 ID를 사용하고 있는지 확인합니다. - (선택사항) 앱이 Apple App Store에 게시된 경우 앱의 App Store ID를 입력합니다. 스토어 ID는 모든 Apple 앱 스토어 URL에 포함된 숫자 문자열입니다.
- (선택사항) 팀 ID를 입력합니다. Apple 개발자 계정 문서의 팀 ID 찾기를 참조하세요. 클라이언트에 앱 체크를 사용 설정하는 경우 팀 ID가 필요합니다.
- (선택사항) iOS 앱에 앱 체크를 사용 설정합니다. 앱 체크를 사용 설정하면 Apple의 App Attest 서비스를 사용하여 OAuth 클라이언트에서 발생하는 OAuth 2.0 요청이 정품이고 앱에서 전송되었는지 확인하므로 앱 가장의 위험을 줄일 수 있습니다.
- 만들기를 클릭합니다.
클라이언트 ID가 생성되어 Google Cloud 콘솔에 표시됩니다. 승인 리디렉션을 처리하려면 반전된 클라이언트 ID URL 스키마 (예: com.googleusercontent.apps.1234567890-abcdef)를 앱의 Info.plist에 추가합니다.
3. 기본 Google 로그인 통합 완료
추가 범위를 요청하고 Google API를 호출하기 전에 기본 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];
}];
액세스 토큰을 사용하여 API를 호출합니다. REST 또는 gRPC 요청의 헤더에 액세스 토큰을 포함하거나(Authorization: Bearer ACCESS_TOKEN) Google API 클라이언트 라이브러리와 함께 가져오기 승인자를 사용합니다.