Truy cập các API của Google trong ứng dụng iOS

Một số dịch vụ của Google, chẳng hạn như Drive, Gmail và nhiều dịch vụ khác, cung cấp các API công khai mà bạn có thể sử dụng để tạo ứng dụng giúp người dùng làm việc với dữ liệu của họ trong luôn miễn phí. Để truy cập các dịch vụ này, ứng dụng phải triển khai một trong các OAuth 2.0 luồng ứng dụng khách để có được sự đồng ý của người dùng và nhận mã truy cập, cấp quyền truy cập vào các API.

Bạn có thể sử dụng thư viện Đăng nhập bằng Google. Thư viện này triển khai quy trình OAuth 2.0 cho bạn để nhận mã truy cập cho người dùng đã đăng nhập.

Trước khi bắt đầu

Bạn phải hoàn tất quy trình tích hợp tính năng Đăng nhập bằng Google cơ bản.

1. Kiểm tra những phạm vi đã được cấp

Trước khi thực hiện lệnh gọi đến Google API, hãy kiểm tra xem phạm vi nào đã được được cấp cho ứng dụng của bạn bằng cách sử dụng thuộc tính grantedScopes của 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
}

Dựa vào việc người dùng đã cấp một phạm vi nhất định hay chưa, bạn có thể yêu cầu một phạm vi bổ sung để hỗ trợ một phạm vi tương tác.

2. Yêu cầu thêm phạm vi

Nếu bạn cần yêu cầu thêm phạm vi, hãy gọi addScopes:presentingViewController:completion hoặc addScopes:presentingWindow:completion để yêu cầu người dùng cấp cho ứng dụng của bạn quyền truy cập bổ sung.

Ví dụ: để yêu cầu quyền chỉ có thể đọc đối với các tệp trên Drive của người dùng:

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. Thực hiện lệnh gọi API bằng mã thông báo mới

Để đảm bảo rằng các lệnh gọi API của Google luôn có mã truy cập chưa hết hạn đính kèm, hãy gói lệnh gọi trong một khối 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];
}];

Sử dụng mã truy cập để gọi API bằng cách đưa mã truy cập vào tiêu đề của một yêu cầu REST hoặc gRPC (Authorization: Bearer ACCESS_TOKEN), hoặc bằng cách sử dụng trình uỷ quyền trình tìm nạp với Thư viện ứng dụng API của Google.