如何使用objective-c获取Gmail api的访问令牌

时间:2016-08-07 23:11:08

标签: objective-c oauth-2.0 google-api gmail gmail-api

以下代码

- (void)viewDidLoad {
[super viewDidLoad];

// Create a UITextView to display output.
self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
self.output.editable = false;
self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.output];

// Initialize the Gmail API service & load existing credentials from the keychain if available.
self.service = [[GTLServiceGmail alloc] init];
self.service.authorizer =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                      clientID:kClientID
                                                  clientSecret:nil];

[GIDSignIn sharedInstance].clientID = kClientID;
[[GIDSignIn sharedInstance] signInSilently];
NSLog(@"token: %@", [GIDSignIn sharedInstance].currentUser.authentication.accessToken);
}

- (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: %@", [GIDSignIn sharedInstance].currentUser.authentication.accessToken, [GIDSignIn sharedInstance].currentUser.userID);
    [self dismissViewControllerAnimated:YES completion:nil];

   }
}

当我尝试输出访问令牌和userID时,总是在日志中给我一个'token:(null)id:(null)'。但是,授权很好。 有人能告诉我什么是错的,如何正确获取访问令牌?

1 个答案:

答案 0 :(得分:2)

更改此行:

NSLog(@"Token: %@ id: %@", [GIDSignIn sharedInstance].currentUser.authentication.accessToken, [GIDSignIn sharedInstance].currentUser.userID);

进入这个:

NSLog(@"Token: %@ id: %@", authResult.accessToken, authResult.userID);