iOS uygulamasında Google API'lerine erişme

Drive ve Gmail gibi bazı Google hizmetleri, kullanıcıların bu hizmetlerdeki verileriyle çalışmasına yardımcı olan uygulamalar oluşturmak için kullanabileceğiniz, herkese açık API'ler sağlar. Bu hizmetlere erişmek için uygulamaların kullanıcılardan izin almak ve API'lere erişim sağlayan erişim jetonları almak üzere OAuth 2.0 istemci akışlarından birini uygulaması gerekir.

Oturum açmış kullanıcının erişim jetonlarını almak için sizin için OAuth 2.0 akışını uygulayan Google ile Oturum Açma kitaplığını kullanabilirsiniz.

Başlamadan önce

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

1. Hangi kapsamların verildiğini kontrol etme

Bir Google API'sine çağrı yapmadan önce GIDGoogleUser öğesinin grantedScopes özelliğini kullanarak uygulamanıza hangi kapsamların verildiğini kontrol edin:

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ın verilip verilmediğine bağlı olarak, belirli bir etkileşimi desteklemek için ek kapsam talep etmeniz gerekebilir.

2. Ek kapsam isteme

Ek kapsam istemeniz gerekirse kullanıcıdan uygulamanıza ek erişim izni vermesini istemek için addScopes:presentingViewController:completion veya addScopes:presentingWindow:completion numaralı telefonu arayın.

Ö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 bir API çağrısı yapın

Google API çağrılarınıza her zaman süresi dolmamış erişim jetonları eklendiğinden emin olmak için ç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ığına ekleyerek veya Google API'leri İstemci Kitaplığı ile alıcı yetkilendiriciyi kullanarak API'yi çağırmak için erişim jetonunu kullanın.