3

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?

Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • The second is simpler and probably harder to muck up, especially if you're juggling a lot of requests. Not quite a flexible as the first. – Hot Licks Mar 23 '13 at 20:36

2 Answers2

7

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)
XJones
  • 21,959
  • 10
  • 67
  • 82
1

Use the first one. You have a method which is telling you when the connection has finished, then you can perform another method to display the data or whatever you plan on doing with it.

Kris Gellci
  • 9,539
  • 6
  • 40
  • 47
  • 2
    `stringWithContentsOfURL:encoding:error:` is synchronous so when it returns the request is complete. You can then post a notification to the main thread to display the result in UI. There are other reasons why I prefer `NSURLConnection` however. – XJones Mar 23 '13 at 20:23
  • It is true, you can do that, but it is simpler to use something built with delegate methods that let you know when completion has occurred. – Kris Gellci Mar 23 '13 at 20:26