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

How to get access token for Gmail api using objective-c

代码如下

- (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];

   }
}

当我尝试输出访问令牌和用户 ID 时,总是在日志中给我一个“token: (null) id: (null)”。但是,授权没问题。 谁能告诉我哪里出了问题,如何正确获取访问令牌?

更改此行:

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

进入这个:

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