Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON requests in iOS - use Grand Central Dispatch or NSURLConnection

I saw several tutorials on making JSON requests in iOS, many of them listed something like this using NSURLConnection:

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

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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {}

But I read another tutorial today (http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-interacting-with-web-services/) where it had this beautifully simple implementation:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    NSError *error = nil;
    NSURL *url = [NSURL URLWithString:@"http://brandontreb.com/apps/pocket-mud-pro/promo.json"];
    NSString *json = [NSString stringWithContentsOfURL:url
                                              encoding:NSASCIIStringEncoding
                                                 error:&error];
    NSLog(@"\nJSON: %@ \n Error: %@", json, error);
});

Which one would be better to use? Is there one inherently wrong with the simplicity of the latter?

like image 946
Doug Smith Avatar asked Dec 30 '25 13:12

Doug Smith


1 Answers

There is nothing "wrong" with the using stringWithContentsOfURL:encoding:error: but you have no flexibility in how you handle a request in progress. If you need to do any of the following then I would use NSURLConnection:

  1. display a completion % to users during a request
  2. perform a request to a host requiring HTTP authentication
  3. more complicated data handling (e.g. downloading more data than a typical JSON response from a web service) where you may want to handle the response in chunks
  4. cancel the request (thanks @martin)
like image 110
XJones Avatar answered Jan 02 '26 05:01

XJones