ArtStyle ArtStyle - 1 year ago 121
iOS Question

Get access token for gmail api via objective-c

I used the code from this sample. To get the number of user's unread messages (that's what I need), I need to send this


like in this example. But I guess that the
should be here instead of
. If so, could anybody tell me how to get the access token using AFNetworking or auth from the sample?

Answer Source

To get the access token to make an authorize request to the Google API you should implement the following methods:

- (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:@" "]
return authController;

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
  finishedWithAuth:(GTMOAuth2Authentication *)authResult
             error:(NSError *)error {
if (error != nil) {
else {
    NSLog(@"Access token: %@", authResult.accessToken);


And your ViewDidAppear method should looks like this:

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

That code output the target access token.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download