Dostęp do interfejsów API Google w aplikacji na iOS

Niektóre usługi Google, takie jak Dysk, Gmail i wiele innych, zapewniają publiczne interfejsy API, które można wykorzystać 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ą wdrożyć jeden z procesó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.

Możesz użyć biblioteki logowania przez Google, która implementuje proces OAuth 2.0 za Ciebie, aby uzyskać tokeny dostępu dla zalogowanego użytkownika.

Zanim zaczniesz

Musisz przejść podstawową integrację logowania przez Google.

1. Sprawdź, które zakresy zostały przyznane

Zanim wywołasz interfejs Google API, sprawdź, jakie zakresy zostały już przypisane do Twojej aplikacji, używając właściwości grantedScopes 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 użytkownik przyznał określony zakres, konieczne może być przesłanie prośby o dodatkowy zakres w celu obsługi konkretnej interakcji.

2. Poproś o dodatkowe zakresy

Jeśli chcesz poprosić o dodatkowe zakresy, wywołaj funkcję addScopes:presentingViewController:completion lub addScopes:presentingWindow:completion, aby poprosić użytkownika o przyznanie Twojej 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. Tworzenie wywołania interfejsu API z nowymi tokenami

Aby mieć pewność, że do wywołań interfejsu API Google zawsze będą dołączone aktualne tokeny dostępu, umieść je blokiem 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];
}];

Do wywoływania interfejsu API użyj tokena dostępu. Aby to zrobić, umieść token dostępu w nagłówku żądania REST lub gRPC (Authorization: Bearer ACCESS_TOKEN) albo użyj narzędzia do pobierania z biblioteką klienta interfejsów API Google.