Created
December 4, 2014 19:40
-
-
Save lborsato/cb21ac6373728e38767c to your computer and use it in GitHub Desktop.
iOS HTTP Post request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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