

Ok, this is gonna be short, I promise! ๐
Do you remember those apps you’ve got stored away or the ones you are working on that fetch data from the web with a NSURLConnection? Time to update them, here’s how.
Basically you have a method that calls a web fetch and is somehow signaled to use that received data to refresh a UI. If you used NSURLConnection sendAsynchronousRequest:, you have the issue that it blocks the main thread. It does carry out requests asynchronously from each other, but each request does indeed block the main thread since it is carried out in the main queue. Alternatively, you can use a long brittle bunch of API’s named NSURLConnection initWithRequest: with a set of delegate callbacks. Instead, take a look at this.
If you have:
-(void)fetchDataFromWeb{
//1. LOAD DATA FROM WEB
NSURL *stringURL = [NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:stringURL];
[NSURLConnection sendAsynchronousRequest:myRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Once data is got, load local object & fire reloadData
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//UPDATE CURRENT VIEW FIRST
[self setData];
}];
}
Replace with:
-(void)fetchDataFromWeb{
//1. LOAD DATA FROM WEB
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"]
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
// handle response
//Once data is got, load local object & fire reloadData
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//UPDATE CURRENT VIEW FIRST
[self setData];
}] resume];
}
The most important thing to note here, is perhaps an little noticed piece of code in NSURLConnection, queue:[NSOperationQueue mainQueue].
You see, other than that, the both pieces of code do pretty much the same thing. They fetch data. NSURLConnection fetches data but it will block your main thread. This means that if you call the fetch, your app will stop or hand until the NSURLResponse is received.
You could go this route:
1. Adopt the delegate:
& create a data container NSMutableData *_responseData;
2. Call your web fetch:
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"]];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
3. Get your data from the callbacks:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
– (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
– (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//UPDATE CURRENT VIEW FIRST
[self setData];
}
– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
}
That’s a BIG block of code! And it can get tedious & brittle to maintain.
NSURLSession automatically calls the web fetch in a background thread so as to not block your main thread. How cool is that? ๐ Enjoy!
Fetching data from an iOS app
[…]It tells me I need an update but only gets halfway through says it can’t be done. I agree with Dee I need help with this.[…]