Niektóre usługi Google, takie jak Dysk, Gmail i wiele innych, oferują publiczne interfejsy API, których możesz używać do tworzenia aplikacji ułatwiających pracę z danymi w tych usługach. Aby można było uzyskiwać dostęp do tych usług, aplikacje muszą wdrożyć jeden z procesów klienta OAuth 2.0 w celu uzyskania zgody użytkowników oraz uzyskania tokenów dostępu, które przyznają dostęp do interfejsów API.
Jeśli chcesz uzyskać tokeny dostępu zalogowanego użytkownika, możesz użyć biblioteki logowania Google, która implementuje protokół OAuth 2.0.
Zanim zaczniesz
Musisz przeprowadzić podstawową integrację z logowaniem przez Google.
1. Sprawdź, które zakresy zostały przyznane
Przed wywołaniem interfejsu API Google sprawdź za pomocą właściwości grantedScopes
GIDGoogleUser
, które zakresy zostały już przydzielone aplikacji:
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
}
W zależności od tego, czy użytkownik przyznał określony zakres, w celu obsługi określonej interakcji może być konieczne wysłanie żądania o dodatkowy zakres.
2. Poproś o dodatkowe zakresy
Jeśli chcesz poprosić o dodatkowe zakresy, wywołaj metodę addScopes:presentingViewController:completion
lub addScopes:presentingWindow:completion
i poproś użytkownika o przyznanie aplikacji dodatkowego dostępu.
Aby na przykład poprosić o dostęp tylko do odczytu do plików użytkownika na Dysku:
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. Wywołanie interfejsu API przy użyciu nowych tokenów
Aby wywołania Google API zawsze miały dołączone tokeny dostępu, które mieszczą się, umieść je w bloku 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];
}];
Użyj tokena dostępu do wywołania interfejsu API, dodając ten token w nagłówku żądania REST lub gRPC (Authorization: Bearer ACCESS_TOKEN
) albo za pomocą modułu autoryzacji modułu pobierania z biblioteką klienta interfejsów API Google.