Mengakses Google API di aplikasi iOS

Beberapa layanan Google, seperti Drive, Gmail, dan banyak layanan lainnya menyediakan API publik yang dapat digunakan untuk membuat aplikasi yang membantu pengguna menangani data mereka di layanan ini. Untuk mengakses layanan ini, aplikasi harus menerapkan salah satu alur klien OAuth 2.0 untuk mendapatkan izin dari pengguna dan mendapatkan token akses, yang memberikan akses ke API.

Anda dapat menggunakan library Login dengan Google, yang menerapkan alur OAuth 2.0 untuk Anda, guna mendapatkan token akses untuk pengguna yang login.

Sebelum memulai

Anda harus menyelesaikan integrasi Login dengan Google dasar.

1. Memeriksa cakupan mana yang telah diberikan

Sebelum melakukan panggilan ke Google API, periksa cakupan mana yang telah diberikan ke aplikasi Anda menggunakan properti grantedScopes dari 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
}

Berdasarkan apakah cakupan tertentu telah diberikan oleh pengguna atau tidak, Anda mungkin harus mengajukan permintaan untuk cakupan tambahan agar dapat mendukung interaksi tertentu.

2. Meminta cakupan tambahan

Jika Anda perlu meminta cakupan tambahan, panggil addScopes:presentingViewController:completion atau addScopes:presentingWindow:completion untuk meminta pengguna memberi akses tambahan ke aplikasi Anda.

Misalnya, untuk meminta akses hanya baca ke file Drive pengguna:

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. Melakukan panggilan API dengan token baru

Untuk memastikan panggilan Google API Anda selalu memiliki token akses yang belum habis masa berlakunya, gabungkan panggilan dalam blok 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];
}];

Gunakan token akses untuk memanggil API, dengan menyertakan token akses di header permintaan REST atau gRPC (Authorization: Bearer ACCESS_TOKEN), atau dengan menggunakan pengambil otorisasi dengan Library Klien Google API.