دسترسی به APIهای Google در یک برنامه iOS

برخی از سرویس‌های گوگل، مانند درایو، جیمیل و بسیاری دیگر، APIهای عمومی ارائه می‌دهند که می‌توانید از آنها برای ایجاد برنامه‌هایی استفاده کنید که به کاربران کمک می‌کند تا با داده‌های خود در این سرویس‌ها کار کنند. برای دسترسی به این سرویس‌ها، برنامه‌ها باید یکی از جریان‌های کلاینت OAuth 2.0 را پیاده‌سازی کنند تا رضایت کاربران را دریافت کرده و توکن‌های دسترسی را که دسترسی به APIها را اعطا می‌کنند، دریافت کنند.

شما می‌توانید از کتابخانه Google Sign-In که جریان OAuth 2.0 را برای شما پیاده‌سازی می‌کند، برای دریافت توکن‌های دسترسی برای کاربر وارد شده استفاده کنید.

قبل از اینکه شروع کنی

شما باید یکپارچه‌سازی اولیه ورود به سیستم با گوگل را تکمیل کنید.

۱. بررسی کنید که کدام حوزه‌ها اعطا شده‌اند

قبل از اینکه یک API گوگل را فراخوانی کنید، با استفاده از ویژگی grantedScopes از GIDGoogleUser ، بررسی کنید که کدام حوزه‌ها (scope) قبلاً به برنامه شما اعطا شده‌اند:

سویفت

let driveScope = "https://www.googleapis.com/auth/drive.readonly"
let grantedScopes = user.grantedScopes
if grantedScopes == nil || !grantedScopes!.contains(driveScope) {
  // Request additional Drive scope.
}

هدف-سی

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
}

بسته به اینکه آیا یک محدوده خاص توسط کاربر اعطا شده است یا خیر، ممکن است لازم باشد برای پشتیبانی از یک تعامل خاص، درخواستی برای یک محدوده اضافی ارسال کنید.

۲. درخواست اسکوپ‌های اضافی

اگر نیاز به درخواست scopeهای اضافی دارید، addScopes:presentingViewController:completion یا addScopes:presentingWindow:completion فراخوانی کنید تا از کاربر بخواهید دسترسی‌های بیشتری به برنامه شما اعطا کند.

برای مثال، برای درخواست دسترسی فقط خواندنی به فایل‌های Drive یک کاربر:

سویفت

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.
}

هدف-سی

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

۳. با توکن‌های جدید، یک فراخوانی API انجام دهید

برای اطمینان از اینکه فراخوانی‌های API گوگل شما همیشه توکن‌های دسترسی منقضی نشده را به همراه دارند، فراخوانی‌ها را در یک بلوک refreshTokensIfNeededWithCompletion: قرار دهید:

سویفت

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()
}

هدف-سی

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

از توکن دسترسی برای فراخوانی API استفاده کنید، یا با قرار دادن توکن دسترسی در هدر درخواست REST یا gRPC ( Authorization: Bearer ACCESS_TOKEN ) یا با استفاده از مجوز دهنده‌ی واکشی با کتابخانه‌ی کلاینت APIهای گوگل .