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 aiutano gli utenti a lavorare con 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 concedono l'accesso alle API.

Puoi utilizzare la libreria Google Sign-In, che implementa il flusso OAuth 2.0 per te, per ottenere i token di accesso per l'utente che ha eseguito l'accesso.

Prima di iniziare

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

1. Controlla quali ambiti sono stati concessi

Prima di effettuare una chiamata a un'API 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 un determinato ambito sia stato concesso o meno dall'utente, potrebbe essere necessario richiedere un ambito aggiuntivo per supportare una determinata interazione.

2. Richiedi ambiti aggiuntivi

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

Ad esempio, per richiedere l'accesso in 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. Esegui una chiamata API con token aggiornati

Per assicurarti che le chiamate alle API Google abbiano sempre token di accesso non scaduti, racchiudi 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 includendolo nell'intestazione di una richiesta REST o gRPC (Authorization: Bearer ACCESS_TOKEN) o utilizzando l'autorizzatore fetcher con la libreria client delle API Google.