Aug 29, 2010 / iphone
iPhone Tip: Always Download Data Asynchronously. Always.

Most iPhone apps I have worked on need to grab xml, json or images from a web service.

If you do anything like this...

NSData *data = [NSData initWithURL: someUrl];

...you're going to get in trouble. Much of the handy "grab some data from the web" methods in the iPhone SDK work synchronously, and block the UI thread. This means that your users won't be able to do anything with your app whilst the remote data is downloading. UX fail.

It's really tempting to use these synchronous methods because they're so easy. Seriously, DON'T DO THIS!!! Not for thumbnails. Not for tiny xml files. Not for files coming from a blazing fast server over a 1TB pipe. Not anywhere :)

So what do you do? Use an async technology instead. I'm enjoying using Seriously right now, it's very easy. If you like Javascript, you'll probably appreciate the use of blocks to handle different outcomes. It's really straight forward.

Example (from the README):

NSString *url = @"http://api.twitter.com/1/users/show.json?screen_name=probablycorey;"

[Seriously get:url handler:^(id body, NSHTTPURLResposne *response, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    }
    else {
        NSLog(@"Look, JSON is parsed into a dictionary!");
        NSLog(@"%@", [body objectForKey:@"profile_background_image_url"]);
    }
}];

Obviously a quick Google search should find you tons of other libraries for asnc calls you might prefer.


You may also like...