I am writing an app that’s a very simple web service cl开发者_开发技巧ient. I have the following questions: 1. Is there a standard common way to write the web service consumption part so that it won’t interfere with the main GUI thread? Is it common practice to use the main thread considering the web request should take a very short time to complete (but never know)? Any links to tutorials? 2. All examples I saw call the web service via GET. I need to POST the data to the web service. Any known samples/tutorials that use POST?
If you're using the iPhone's built-in web request API, NSURLConnection, you run the request on the main thread but you run it asynchronously, with callbacks to a delegate as data is returned. This leaves the application responsive to user events. If the parsing or processing of the returned data takes too long to run on the main thread then you should run the NSURLConnection on the main thread, then hand off response data either incrementally or after the download is complete to a secondary thread for pure compute processing.
It is possible to start NSURLConnections on a non-main thread but you'll need to create a runloop on the non-main thread, and there are reports of random thread-safety bugs in the Apple libraries. If you really need to run the request itself on a non-main thread you can use the third party library ASIHTTPRequest, but you shouldn't need to do this except in very specialized circumstances.
Generating a POST request is straightforward with NSURLConnection:
NSString * requestBody = @"format up your body here, which is often form-urlencoded";
NSURL * nsurl = [NSURL URLWithString: @"http://example.com/post_request_receiver"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:nsurl];
// set appropriate content type here, usually application/x-www-form-urlencoded
[theRequest addValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: [NSString stringWithFormat:@"%d", [requestBody length]] forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [requestBody dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
精彩评论