重要提示:自
2024 年 5 月 1 日起,对于使用常用 SDK(包括 GoogleSignIn-iOS)的 iOS 应用,Apple
要求提供隐私权清单和签名。请在 2024 年 5 月 1 日之前升级到 GoogleSignIn-iOS v7.1.0 及更高版本。按照
我们的升级指南操作。
在 iOS 应用中访问 Google API
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
某些 Google 服务(例如云端硬盘、Gmail 等)提供公共 API
您可以用它来创建应用,帮助用户在 Google Cloud 中
服务。要访问这些服务,应用必须实现 OAuth 2.0
客户端流程来获得用户同意,并获取访问令牌,
对 API 的访问权限。
您可以使用 Google 登录库,它为
来获取已登录用户的访问令牌。
准备工作
您必须完成基本的 Google 登录功能集成。
1. 查看已授予的范围
在调用 Google API 之前,请检查哪些范围已被使用
(使用 GIDGoogleUser
的 grantedScopes
属性授予您的应用):
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
,请求用户授予您的应用
额外访问权限。
例如,要请求以只读方式访问用户的云端硬盘文件,请执行以下操作:
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 API 客户端库。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-25。
[null,null,["最后更新时间 (UTC):2025-07-25。"],[[["\u003cp\u003eGoogle services like Drive and Gmail offer public APIs for building apps that interact with user data, requiring OAuth 2.0 for user consent and access tokens.\u003c/p\u003e\n"],["\u003cp\u003eBefore making API calls, verify granted scopes using \u003ccode\u003egrantedScopes\u003c/code\u003e and request additional scopes if needed with \u003ccode\u003eaddScopes\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eEnsure API calls have unexpired access tokens by wrapping them in \u003ccode\u003erefreshTokensIfNeededWithCompletion\u003c/code\u003e to refresh tokens.\u003c/p\u003e\n"],["\u003cp\u003eAccess tokens can be used directly in REST/gRPC requests or with the Google APIs Client Library for seamless integration.\u003c/p\u003e\n"],["\u003cp\u003eBasic Google Sign-In integration is a prerequisite before using these features.\u003c/p\u003e\n"]]],[],null,["# Access Google APIs in an iOS app\n\nSome Google services, such as Drive, Gmail, and many others, provide public APIs\nthat you can use to create apps that help users work with their data in these\nservices. To access these services, apps must implement one of the OAuth 2.0\nclient flows to get consent from users and obtain *access tokens*, which grant\naccess to the APIs.\n\nYou can use the Google Sign-In library, which implements the OAuth 2.0 flow for\nyou, to get access tokens for the signed-in user.\n\nBefore you begin\n----------------\n\nYou must complete the [basic Google Sign-In integration](/identity/sign-in/ios/sign-in).\n\n1. Check which scopes have been granted\n---------------------------------------\n\nBefore you make a call to a Google API, check which scopes have already been\ngranted to your app, using the `grantedScopes` property of `GIDGoogleUser`: \n\n### Swift\n\n let driveScope = \"https://www.googleapis.com/auth/drive.readonly\"\n let grantedScopes = user.grantedScopes\n if grantedScopes == nil || !grantedScopes!.contains(driveScope) {\n // Request additional Drive scope.\n }\n\n### Objective-C\n\n NSString *driveScope = @\"https://www.googleapis.com/auth/drive.readonly\";\n\n // Check if the user has granted the Drive scope\n if (![user.grantedScopes containsObject:driveScope]) {\n // request additional drive scope\n }\n\nBased on whether or not a certain scope has been granted by the user, you might\nneed to make a request for an additional scope in order to support a particular\ninteraction.\n\n2. Request additional scopes\n----------------------------\n\nIf you need to request additional scopes, call\n`addScopes:presentingViewController:completion` or\n`addScopes:presentingWindow:completion` to ask the user to grant your app\nadditional access.\n\nFor example, to request read-only access to a user's Drive files: \n\n### Swift\n\n let additionalScopes = [\"https://www.googleapis.com/auth/drive.readonly\"]\n guard let currentUser = GIDSignIn.sharedInstance.currentUser else {\n return ; /* Not signed in. */\n }\n\n currentUser.addScopes(additionalScopes, presenting: self) { signInResult, error in\n guard error == nil else { return }\n guard let signInResult = signInResult else { return }\n\n // Check if the user granted access to the scopes you requested.\n }\n\n### Objective-C\n\n NSArray *additionalScopes = @[ @\"https://www.googleapis.com/auth/drive.readonly\" ];\n GIDGoogleUser *currentUser = GIDSignIn.sharedInstance.currentUser;\n\n [currentUser addScopes:additionalScopes\n presentingViewController:self\n completion:^(GIDSignInResult * _Nullable signInResult,\n NSError * _Nullable error) {\n if (error) { return; }\n if (signInResult == nil) { return; }\n\n // Check if the user granted access to the scopes you requested.\n }];\n\n3. Make an API call with fresh tokens\n-------------------------------------\n\nTo ensure that your Google API calls always have unexpired access tokens\nattached, wrap the calls in a `refreshTokensIfNeededWithCompletion:` block: \n\n### Swift\n\n currentUser.refreshTokensIfNeeded { user, error in\n guard error == nil else { return }\n guard let user = user else { return }\n\n // Get the access token to attach it to a REST or gRPC request.\n let accessToken = user.accessToken.tokenString\n\n // Or, get an object that conforms to GTMFetcherAuthorizationProtocol for\n // use with GTMAppAuth and the Google APIs client library.\n let authorizer = user.fetcherAuthorizer()\n }\n\n### Objective-C\n\n [currentUser refreshTokensIfNeededWithCompletion:^(\n GIDGoogleUser * _Nullable user,\n NSError * _Nullable error) {\n if (error) { return; }\n if (user == nil) { return; }\n\n // Get the access token to attach it to a REST or gRPC request.\n NSString *accessToken = user.accessToken.tokenString;\n\n // Or, get an object that conforms to GTMFetcherAuthorizationProtocol for\n // use with GTMAppAuth and the Google APIs client library.\n id\u003cGTMFetcherAuthorizationProtocol\u003e authorizer = [user fetcherAuthorizer];\n }];\n\nUse the access token to call the API, by either including the access token in\nthe header of a REST or gRPC request (`Authorization: Bearer `\u003cvar translate=\"no\"\u003eACCESS_TOKEN\u003c/var\u003e),\nor by using the fetcher authorizer with the\n[Google APIs Client Library](https://github.com/google/google-api-objectivec-client-for-rest/)."]]