Search code examples
iosobjective-cgmailafnetworkinggmail-api

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 GET request

https://www.googleapis.com/gmail/v1/users/me/labels/UNREAD?key={MY_API_KEY}

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


Solution

  • 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:@" "]
                      clientID:kClientID
                      clientSecret:nil
                      keychainItemName:kKeychainItemName
                      delegate:self
                      finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    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.