开发者

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:

  1. Use the very excellent ASIHTTPRequest helper class from http://allseeing-i.com/ASIHTTPRequest/
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜