8vius 8vius - 4 months ago 35
Objective-C Question

iOS - Make POST request to CakePHP REST

I'm looking for how to do a POST request to a REST web service, specifically a CakePHP service and all I seem to find is people saying to use the ASIHTTPRequest library, but I see that's not been updated in a year or so, so I'd rather use a more up to date method, preferably directly from iOS.

I read you can make the call using NSURLConnection but I really don't understand it, I would like a more thorough explanation of it, if someone could point me in the right direction.

Also I have already successfully retrieved data from my server using my REST API by using NSString's stringWithContentOfURL method, but I can't use this to make a POST call as far as I know.

Answer

I usually do it like this.

NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:self.yourData];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
    // Process response
} else {
    // Process error
}

[NSURLConnection sendSynchronousRequest:] method also returns NSData object which you too can manipulate.