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