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);
});
}
});
}