גישה ל-Google APIs באפליקציה ל-iOS

חלק משירותי Google, כמו Drive, Gmail ורבים אחרים, מספקים ממשקי API ציבוריים שבהם אפשר להשתמש כדי ליצור אפליקציות שעוזרות למשתמשים לעבוד עם הנתונים שלהם בשירותים האלה. כדי לקבל גישה לשירותים האלה, צריך להטמיע באפליקציות אחד מתהליכי העבודה של לקוחות OAuth 2.0 כדי לקבל הסכמה מהמשתמשים ולהשיג אסימוני גישה שמעניקים גישה לממשקי ה-API.

תוכלו להשתמש בספריית 'כניסה באמצעות חשבון Google', שמטמיעה בשבילכם את תהליך OAuth 2.0, כדי לקבל אסימוני גישה עבור המשתמש המחובר.

לפני שמתחילים

עליכם להשלים את השילוב הבסיסי של כניסה באמצעות חשבון Google.

1. בדיקה אילו היקפים הוענקו

לפני שמבצעים קריאה ל-Google API, צריך לבדוק אילו היקפים כבר הוענקו לאפליקציה באמצעות המאפיין grantedScopes של 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
}

יכול להיות שתצטרכו להגיש בקשה להיקף נוסף כדי לתמוך באינטראקציה מסוימת, בהתאם להיקף הספציפי שהמשתמשים העניקו לו.

2. בקשה להיקפים נוספים

אם אתם צריכים לבקש היקפים נוספים, תוכלו להתקשר אל addScopes:presentingViewController:completion או אל addScopes:presentingWindow:completion כדי לבקש מהמשתמש להעניק לאפליקציה שלכם הרשאת גישה נוספת.

לדוגמה, כדי לבקש הרשאת קריאה בלבד לקובצי Drive של משתמש:

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. ביצוע קריאה ל-API עם אסימונים חדשים

כדי לוודא שלקריאות ל-Google API יהיו תמיד אסימוני גישה לא תקפים, צריך להקיף את הקריאות בבלוק 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];
}];

אפשר להשתמש באסימון הגישה כדי להפעיל את ה-API על ידי הכללת אסימון הגישה בכותרת של בקשת REST או gRPC (Authorization: Bearer ACCESS_TOKEN) או על ידי שימוש בהרשאת האחזור באמצעות ספריית הלקוח של Google APIs.