גישה ל-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.