我通过这种方法获得访问令牌:
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)authResult
error:(NSError *)error {
if (error != nil) {
[self showAlert:@"Authentication Error" message:error.localizedDescription];
self.service.authorizer = nil;
}
else {
self.service.authorizer = authResult;
NSLog(@"Token: %@ id: %@", authResult.accessToken, authResult.userID);
[self makeGmailLabelVisibleWithToken:authResult.accessToken]; //make an authorized request to gmailAPI with the access token
[self dismissViewControllerAnimated:YES completion:nil];
}
}
因此,经过auth可以正常工作,但是一段时间后它停止工作(我想是因为令牌已过期)。另外,如果我使用
[authResult refreshToken]
代替
authResult.accessToken
它不会工作。
那么刷新Gmail访问令牌的正确方法是什么,我应该采用哪种方法?
PS:文档说
- (void) refreshTokensWithHandler:(GIDAuthenticationHandler)handler
应该有帮助,但是我还没有找到任何样品。
因此,这实际上很简单。要刷新令牌,您需要使用以下代码:
self.service = [[GTLServiceGmail alloc] init];
self.service.authorizer =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:nil];
[[GIDSignIn sharedInstance] setScopes:[NSArray arrayWithObject: @"https://www.googleapis.com/auth/plus.me"]];
[GIDSignIn sharedInstance].clientID = kClientID;
GTMOAuth2Authentication *auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:nil];
NSLog(@"accessToken: %@", auth.accessToken); //If the token is expired, this will be nil
// authorizeRequest will refresh the token, even though the NSURLRequest passed is nil
[auth authorizeRequest:nil
completionHandler:^(NSError *error) {
if (error) {
NSLog(@"error: %@", error);
}
else {
[USER_CACHE setValue:auth.accessToken forKey:@"googleAccessToken"];
}
}];
您可以将其粘贴到例如ViewDidLoad方法中。因此,执行此代码后,您将在UserDefaults中拥有有效的访问令牌(在我的示例中为USER_CAHCE)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句