Reputation: 393
I've followed some tutorials, but I'm stuck on doing Post requests. I Just want to send 3 parameters, to a URL and hadle with the response. And it has to be asynchronous, because it will give me some images, that i want to but one by one on the view.
Can you help me guys?
Upvotes: 1
Views: 3403
Reputation: 5836
This is well covered here.
But the way I do it I find to be simpler, as I'll show you. Still there are many questions here on SO and other places that provide this knowledge.
First we set up our request with our parameters:
- (NSData *)executePostCall {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", YOUR_URL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *requestFields = [NSString stringWithString:@""];
requestFields = [requestFields stringByAppendingFormat:@"parameter1=%@&", parameter1];
requestFields = [requestFields stringByAppendingFormat:@"parameter2=%@&", parameter2];
requestFields = [requestFields stringByAppendingFormat:@"parameter3=%@", parameter3];
requestFields = [requestFields stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestData = [requestFields dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestData;
request.HTTPMethod = @"POST";
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
NSLog(@"%i", response.statusCode);
} else {
//Error handling
}
return responseData;
}
This has to be wrapped up in a block since we can't execute this on the main thread because it will lock up our application and that is frowned upon, so we do the following to wrap this request up, I'll leave the rest of the details up to you:
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *result = [self executePostCall];
dispatch_async(dispatch_get_main_queue(), ^{
// Handle your resulting data
});
});
dispatch_release(downloadQueue);
Upvotes: 2
Reputation: 40201
Use NSURLRequest
. You can download files in the background and show them once you receive the delegate notification: Downloading to a Predetermined Destination
Upvotes: 0