我使用了this sample中的代码。要获取用户未读消息的数量(这就是我需要的消息),我需要发送此GET
请求
https://www.googleapis.com/gmail/v1/users/me/labels/UNREAD?key={MY_API_KEY}
就像this example一样。但我想{ACCESS_TOKEN}
应该在这里而不是{MY_API_KEY}
。如果是这样,有人可以告诉我如何使用AFNetworking或auth from the sample获取访问令牌吗?
答案 0 :(得分:0)
如Authorizing Your App with Gmail
中所述Gmail使用OAuth 2.0 protocol对Google帐户进行身份验证并授权访问用户数据。您还可以使用Google+ Sign-in为您的应用提供“使用Google登录”身份验证方法。
如果仍然按照您的要求使用AFNetworking,您可以使用指南来了解如何获取此GitHub帖子中提供的访问令牌 - AFOAuth2Manager。
此SO帖子中提供的解决方案 - How to get the number of unread threads in INBOX with Gmail API也可能有所帮助。
答案 1 :(得分:0)
要获取访问令牌以向Google API发出授权请求,您应该实施以下方法:
- (GTMOAuth2ViewControllerTouch *)createAuthController {
GTMOAuth2ViewControllerTouch *authController;
// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeGmailReadonly, nil];
authController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:[scopes componentsJoinedByString:@" "]
clientID:kClientID
clientSecret:nil
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)];
return authController;
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)authResult
error:(NSError *)error {
if (error != nil) {
...
}
else {
NSLog(@"Access token: %@", authResult.accessToken);
}
}
您的ViewDidAppear方法应如下所示:
- (void)viewDidAppear:(BOOL)animated {
if (!self.service.authorizer.canAuthorize) {
// Not yet authorized, request authorization by pushing the login UI onto the UI stack.
[self presentViewController:[self createAuthController] animated:YES completion:nil];
}
该代码输出目标访问令牌。