Pages

Thursday, October 6, 2011

[Code Snippet] Send GET and POST data to web services asynchronously.

Last post talks about sending post and get values to a web service synchronously using NSURLConnection sendSynchronousRequest:(NSURLRequest)request method. Today we'll explain how to do the same request but asynchronously in background.

Firstly, we have to declare some instance variables:


    NSURLConnection *urlConnection;
    NSURL *loginURL;
    NSMutableData *responseData;


The initial code is like synchronous method, we have to prepare the NSURL object, and load the NSMutableURL object with the URL, the parameters and setting the correct headers value.

NSURL *url = [NSURL urlWithString:@"http://www.fiveflamesmobile.com/login.php?from=mobile"];
NSString *formValues = [NSString stringWithFormat:@"name=%@&device=%@", @"FiveFlames", @"iPhone"];
NSData *formData = [formValues dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHttpBody:formData];

And now, instead of invoke sendSynchronousRequest method, we have just to initialize the NSURLConnection object with our request and set the delegate to the class that implements the delegate methods, in this case, our class.


urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

And now we've just to implement the delegate methods. You haven't to put any protocol declaration in .h file.

Basic methdos to implement are:

Will send request is invoked just before to send the request, and we keep the "real" URL stored in our class variable.

- (NSURLRequest *)connection:(NSURLConnection *)connection
             willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
    [urlConnection release];
    urlConnection =  [[request URL] retain];
    
    NSLog(@"URL Recibida: %@:", [[request URL] absoluteString]);
    
    return request;
}

If we have store some data into NSURLRequest HttpBody property, this method will be invoked just after have sent them.

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    NSLog(@"PeticiĆ³n enviada");
}


The method didFailWithError is invoked when the NSURLConnection fails so is time to check the error.

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

The method didReceiveResponse is invoked when the server and the client establish the connection, so we have to initialize here the container in which the response will be saved.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    responseData = [[NSMutableData alloc] init];
    [responseData setLength:0];   
}

This method is invoked when data is received (obviously). If the amount of data is small, it will be invoked once, but if the amount of data is big, this method will be invoked repeatedly. We just to add the received data to the container.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    NSLog(@"Data sin decodificar: %@", data);
}


At last, connectionDidFinishLoading is invoked when the response is totally stored in our variable, so now it's time to log it, parse it or do whatever you want to do with it.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    //Log de la respuesta para depuraciĆ³n
    
    NSString *strResponse = [[NSString alloc] initWithBytes:[responseData bytes]
                                                     length:[responseData length
                                                   encoding:NSUTF8StringEncoding];
    NSLog(@"\n--------- Received Response ---------\n");
    NSLog(@"%@", strResponse);
    NSLog(@"\n--------- End of received response ---------\n");
    
    [strResponse release];
    
}

This is a very basic implementation of an asynchronous request.  We'll try to show you how to make SSL asynchronous connections, but we reserve it for another post.

Enjoy the code!

No comments:

Post a Comment