JSON requests in iOS - use Grand Central Dispatch or NSURLConnection
ios, json, objective-c, xcode
Solution
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`:
- display a completion % to users during a request
- perform a request to a host requiring HTTP authentication
- 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
- cancel the request (thanks @martin)
Problem
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?