Monday, 20 February 2012

Synchronous and Asynchronous Request Processing


Synchronous Request Handling:
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];
NSURLResponse *response = nil;
NSError *error = nil;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//json parse
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [responseString JSONValue];
//Accessing JSON content
NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );
Some explanations :
response is the url response for the json call
error is error returned by NSURLConnection
newData is data returned by the server
Notice that you can cast the JSON deserialized data into a NSDictionnary or anNSMutuableArray.

Asynchronous Request Handling:
To make an Asynchronous call we’ll need to use NSURLConnection withinitWithRequest method, then we need to implement differents other methods to handle the finish of data loading, error handling etc.
//in the viewDidLoad
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/json"]];//asynchronous call
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Implementing delegate methods :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];
    NSDictionary *jsonObject = [responseString JSONValue];
    NSLog(@"type :  %@", [jsonObject objectForKey:@"Type"] );
    [connection release];
}

No comments:

Post a Comment