ArtStyle ArtStyle - 3 months ago 32
Objective-C Question

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

The following code

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

}
}


Always gives me a ' token: (null) id: (null)' in logs when I try to output the access token and userID. However, authorization goes fine.
Could anybody tell me what's wrong, how to get the access token correctly?

Answer

Change this line:

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

into this:

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