Accedi alle API di Google in un'app per iOS

Alcuni servizi Google, come Drive, Gmail e molti altri, forniscono API pubbliche che puoi utilizzare per creare app che consentono agli utenti di utilizzare i propri dati in questi servizi. Per accedere a questi servizi, le app devono implementare uno dei flussi client OAuth 2.0 per ottenere il consenso degli utenti e ottenere token di accesso, che consentono l'accesso alle API.

Puoi utilizzare la libreria Accedi con Google, che implementa il flusso OAuth 2.0 per te, per ricevere token di accesso per l'utente che ha eseguito l'accesso.

Prima di iniziare

Devi completare l'integrazione di base dell'opzione Accedi con Google.

1. Controlla quali ambiti sono stati concessi

Prima di effettuare una chiamata a un'API di Google, controlla quali ambiti sono già stati concessi alla tua app, utilizzando la proprietà grantedScopes di 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
}

A seconda che l'utente abbia concesso o meno un determinato ambito, potrebbe essere necessario effettuare una richiesta di un ambito aggiuntivo per supportare una particolare interazione.

2. Richiedi ambiti aggiuntivi

Se devi richiedere ambiti aggiuntivi, chiama addScopes:presentingViewController:completion o addScopes:presentingWindow:completion per chiedere all'utente di concedere all'app un accesso aggiuntivo.

Ad esempio, per richiedere l'accesso di sola lettura ai file di Drive di un utente:

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. Effettua una chiamata API con token nuovi

Per assicurarti che alle chiamate API di Google siano sempre associati token di accesso non scaduti, aggrega le chiamate in un blocco 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];
}];

Utilizza il token di accesso per chiamare l'API. Includi il token di accesso nell'intestazione di una richiesta REST o gRPC (Authorization: Bearer ACCESS_TOKEN) oppure utilizza l'autorizzazione di recupero con la libreria client delle API di Google.