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ể dùng để tạo ứng dụng giúp người dùng thao tác với dữ liệu của họ trong các dịch vụ này. Để truy cập vào những dịch vụ này, ứng dụng phải triển khai một trong các luồng ứng dụng OAuth 2.0 để có được sự đồng ý của người dùng và có được 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 để lấy 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 cơ bản về tính năng Đăng nhập bằng Google.

1. Kiểm tra xem phạm vi nào đã được cấp

Trước khi bạn thực hiện lệnh gọi đến một API của Google, hãy kiểm tra xem phạm vi nào đã đượ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
}

Tuỳ thuộc 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ể cần yêu cầu một phạm vi bổ sung để hỗ trợ một tương tác cụ thể.

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 thêm quyền truy cập cho ứng dụng.

Ví dụ: để yêu cầu quyền chỉ có thể đọc vào tệp của người dùng trên 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. 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 đính kèm mã truy cập chưa hết hạn, hãy gói các 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 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 tìm nạp cùng với Thư viện ứng dụng API của Google.