Niektóre usługi Google, takie jak Dysk, Gmail i wiele innych, udostępniają publiczne interfejsy API, których możesz używać do tworzenia aplikacji ułatwiających użytkownikom pracę z danymi w tych usługach. Aby uzyskać dostęp do tych usług, aplikacje muszą zaimplementować jeden z przepływów klienta OAuth 2.0 , aby uzyskać zgodę użytkowników i uzyskać tokeny dostępu, które przyznają dostęp do interfejsów API.
Aby uzyskać tokeny dostępu dla zalogowanego użytkownika, możesz użyć biblioteki Logowanie przez Google, która implementuje przepływ OAuth 2.0.
Zanim zaczniesz
Musisz przeprowadzić podstawową integrację Logowania przez Google.
1. Sprawdź, które zakresy zostały przyznane
Zanim wywołasz interfejs API Google, sprawdź, które zakresy zostały już przyznane Twojej aplikacji, używając właściwości grantedScopes obiektu GIDGoogleUser:
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 dany zakres został przyznany przez użytkownika, może być konieczne wysłanie prośby o dodatkowy zakres, aby obsługiwać określoną interakcję.
2. Poproś o dodatkowe zakresy
Jeśli musisz poprosić o dodatkowe zakresy, wywołaj funkcję addScopes:presentingViewController:completion lub addScopes:presentingWindow:completion, aby poprosić użytkownika o przyznanie aplikacji dodatkowego dostępu.
Aby na przykład poprosić o dostęp do plików użytkownika na Dysku tylko do odczytu:
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łaj interfejs API za pomocą nowych tokenów
Aby mieć pewność, że wywołania interfejsów API Google zawsze mają dołączone nieprzeterminowane tokeny dostępu, 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, aby wywołać interfejs API, dołączając go do
nagłówka żądania REST lub gRPC (Authorization: Bearer ACCESS_TOKEN),
albo używając autoryzatora modułu pobierania z
biblioteką klienta interfejsów API Google.