Quite often in my builds I need to get some information from an exposed webservice. Here’s an easy way of doing it with the iPhone API.

In the interface declaration, add a NSMutableData for us to put the response data into:

NSMutableData *responseData;

Then in the viewDidLoad, initialise it:

responseData = [[NSMutableData alloc] init];

When using NSUrlConnection we typically init a NSUrlConnection object from within a method somewhere, or if the information to be retrieved from the webservice, in the viewDidLoad.

NSURL *url = [NSURL URLWithString:@"http://www.mywebservice.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

This sets off the request to the URL specified.

The next part is to implement the delegate methods. There are 4 to do in a typical implementation.

The first, didReceiveResponse, is triggered when when the the first sign of a response comes back. We can check here for errors, or to confirm the service is alive, but all I typically do here is set responseData to zero length.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];

Next, didReceiveData is triggered when data is received back from the call to the webservice. Add this to the responseData.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];

Third, didFailWithError is for any code for when the webservice times out, returns error, or otherwise something bad happens. Typically you can raise an alert to the user here, or in this case suppress it and log it.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"FAIL WITH ERROR: %@", [error description]);

Lastly, connectionDidFinishLoading is run when the webservice has completed. Here you can use the response data to fill a table, display an alert, or whatever else you need.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"All data Received, size %d", [responseData length]);
    NSString *theResponse = [[NSString alloc] initWithBytes:[responseData mutableBytes] length:[responseData length] encoding:NSUTF8StringEncoding];
    NSLog(@"Data returned: %@", theResponse);
    [theResponse release];
    [connection release];
    [responseData release];

Thats it!