Skip to content

Instantly share code, notes, and snippets.

@lborsato
Created December 4, 2014 19:40
Show Gist options
  • Save lborsato/cb21ac6373728e38767c to your computer and use it in GitHub Desktop.
Save lborsato/cb21ac6373728e38767c to your computer and use it in GitHub Desktop.
iOS HTTP Post request
/**
* Do an HTTP POST request and return the results
*
* @param NSString * url the URL
* @param NSString * post the POST data
*
* @return NSDictionary * a dictionary containing the response, error, and data
*/
+ (NSDictionary *)httpPostRequestWithUrl:(NSString *)url post:(NSString *)post
{
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:30]; // set timeout for 30 seconds
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableDictionary *rc = [[NSMutableDictionary alloc] init];
if ( response )
[rc setObject:response forKey:@"response"];
if ( error )
[rc setObject:error forKey:@"error"];
if ( data )
[rc setObject:data forKey:@"data"];
return (NSDictionary *)rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment