Skip to content

Instantly share code, notes, and snippets.

@celian-m
Last active February 28, 2018 13:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celian-m/88c354794fa98923cdc8 to your computer and use it in GitHub Desktop.
Save celian-m/88c354794fa98923cdc8 to your computer and use it in GitHub Desktop.
Generate Twitter Bearer Token

Generate a Bearer token to access Twitter REST API

- (void) generateAPIKeyWithCompletionBlock:(void (^)(BOOL success, NSString* twitterOAuthToken, NSString *error))completion {
    //Network tasks should be in background thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        
        //Generate Bearer Token according to Twitter Documentation
        NSString* bearerToken = [NSString stringWithFormat:@"%@:%@", TWITTER_API_KEY , TWITTER_API_SECRET];
        bearerToken = [[bearerToken dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
        NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
        [request addValue:[NSString stringWithFormat:@"Basic %@",bearerToken] forHTTPHeaderField:@"Authorization"];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[@"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]];
        [request setURL:[NSURL URLWithString:@"https://api.twitter.com/oauth2/token"]];
        NSURLResponse *response;
        NSError* e;
        NSData* data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:&response
                                                         error:&e];
        BOOL success = NO;
        NSString* twitterOAuthToken;
        if(!e && data){
            NSDictionary* answer = [NSJSONSerialization JSONObjectWithData:data options:0 error:&e];
            if(!e && [answer stringForKey:@"access_token"]){
                twitterOAuthToken = [answer stringForKey:@"access_token"];
                success = YES;
            }
        }
        if (completion){
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(success, twitterOAuthToken, e.description);
            });
        }
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment