Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.0.0+

Refresh a Gmail OAuth access token

See more GMail REST API Examples

Use the refresh token and the same Desktop app client that issued it. Run in the private directory used by the authorization example. Preserve the refresh token if Google omits it from the response. Refreshing continues the existing grant. Request additional scopes through interactive authorization.

Google documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoOAuth2.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token LoadFile: @"gmail-token.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not read gmail-token.json from the private working directory.");
    return;
}

if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Authorize the account for offline access first.");
    return;
}

CkoOAuth2 *oauth = [[CkoOAuth2 alloc] init];
oauth.TokenEndpoint = @"https://oauth2.googleapis.com/token";
oauth.ClientId = @"YOUR_DESKTOP_CLIENT_ID";
oauth.ClientSecret = @"YOUR_DESKTOP_CLIENT_SECRET";
oauth.RefreshToken = [token StringOf: @"refresh_token"];
success = [oauth RefreshAccessToken];
if (success != YES) {
    NSLog(@"%@",@"Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.");
    return;
}

CkoJsonObject *fresh = [[CkoJsonObject alloc] init];
success = [fresh Load: oauth.AccessTokenResponse];
if (success != YES) {
    NSLog(@"%@",@"Could not parse the refresh response.");
    return;
}

if (([[fresh JsonTypeOf: @"access_token"] intValue] != 1) || ([fresh StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"The refresh response did not contain an access token.");
    return;
}

if (([[fresh JsonTypeOf: @"refresh_token"] intValue] != 1) || ([fresh StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
    [fresh UpdateString: @"refresh_token" value: [token StringOf: @"refresh_token"]];
}

if (([fresh HasMember: @"scope"] != YES) && ([[token JsonTypeOf: @"scope"] intValue] == 1)) {
    [fresh UpdateString: @"scope" value: [token StringOf: @"scope"]];
}

success = [fresh WriteFile: @"gmail-token.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not save the refreshed credentials.");
    return;
}

NSLog(@"%@",@"Refreshed the access token.");