Simplest way to use REST service
What is the simplest and easiest way, not the best way, to use a REST web service 开发者_开发知识库in an iPhone app? Thanks.
The best I have found so far is as follows:
- Use the very excellent ASIHTTPRequest helper class from http://allseeing-i.com/ASIHTTPRequest/
- Use JSON for your request and response, and parse with http://code.google.com/p/json-framework/
I just added the above classes to my project, and include them where necessary. Then:
NSURL *url = @"http://example.com/rest/whatever";
// create dictionary with post data
NSMutableDictionary *requestDict = [[NSMutableDictionary alloc] init];
[requestDict setObject: Id forKey:@"Id"];
[requestDict setObject: field.text forKey:@"Name"];
//Prepare the http request
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: url];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"raw"];
[request setPostBody: [NSMutableData dataWithData: [[[self sbjson] stringWithObject:requestDict] dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
[requestDict release];
self.error = [request error];
if(self.error)
{
[self performSelectorOnMainThread:@selector(serviceConnectionDidFail) withObject:nil waitUntilDone:NO];
}
else
{
// request succeeded - parse response
NSDictionary *responseDict = [self.sbjson objectWithString:[request responseString]];
int value = [responseDict valueForKey:@"ServerValue"];
}
Its really simple, reliable, and good error handling.
Open safari and navigate to the appropriate URL for the REST server.
精彩评论