iOS uygulamasında Google API'lerine erişme

Drive ve Gmail gibi bazı Google hizmetleri herkese açık API'ler sağlar. Kullanıcıların bu dosyalarda verileriyle çalışmasına yardımcı olacak uygulamalar oluşturmak için kullanıma sunuyoruz. Bu hizmetlere erişmek için uygulamaların OAuth 2.0'dan birini kullanması gerekir erişim jetonları almak ve bu güvenlik açıklarının izin verildiğini göstermek amacıyla ve API'lere erişme.

Şu işlemler için OAuth 2.0 akışını uygulayan Google ile Oturum Açma kitaplığını kullanabilirsiniz: oturum açmış kullanıcıya erişim jetonları almak için

Başlamadan önce

Temel Google ile Oturum Açma entegrasyonunu tamamlamanız gerekir.

1. Hangi kapsamlara izin verildiğini kontrol etme

Bir Google API'sine çağrı yapmadan önce, halihazırda yapılandırılmış olan kapsamları GIDGoogleUser öğesinin grantedScopes özelliği kullanılarak uygulamanıza verildi:

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
}

Kullanıcı tarafından belirli bir kapsam verilip verilmediğine bağlı olarak, desteklemek üzere ek bir kapsam talebinde bulunmanız gerekir. bahsedeceğim.

2. Ek kapsam iste

Ek kapsamlar istemeniz gerekirse addScopes:presentingViewController:completion veya Kullanıcıdan uygulamanıza izin vermesini istemek için addScopes:presentingWindow:completion ek erişim.

Örneğin, bir kullanıcının Drive dosyalarına salt okuma erişimi istemek için:

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. Yeni jetonlarla API çağrısı yapma

Google API çağrılarınızın her zaman süresi dolmamış erişim jetonlarına sahip olmasını sağlamak için ekliyse, çağrıları bir refreshTokensIfNeededWithCompletion: blokunda sarmalayın:

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];
}];

Erişim jetonunu REST veya gRPC isteğinin (Authorization: Bearer ACCESS_TOKEN) başlığı veya Google API'leri İstemci Kitaplığı.