Lazy Internet / Asynchronous Images in iOS

What are asynchronous Images, and why would I want to use it in my app?

You may be aware when coding in xcode for iPhone if you ever want to download a file for the user using [UIImage imageWithData:[NSData dataWithContentsOfURL:@"yoururl"]]; you will find that the application locks up while this loads.

The way around this is to use NSURLConnection, then once the data has been downloaded, to display however you want.

Online libraries

On the web there are lots of different libraries you can add to your app to allow you to download html/text/images in the background, allowing the user to browse around the app while these loads.

A lot of these libraries work well and provide a wealth of functionality, however I could never find a simple library I could start building on. After much deliberation I have created a simple but functional "LazyInternet" class for public use, just include the files at the bottom of this post into your project, then in the interface section of your header file you want to use it in, add #import "LazyInternet.h", and also put a reference for the class into the actual interface (LazyInternet *lazyImage), this should mean your header should look like the example below:

#import <UIKit/UIKit.h>
#import "LazyInternet.h"
@interface ViewController : UIViewController {
    LazyInternet *lazyImage;
    UIImageView *image1;

Once you're done this allocate a new LazyInternet wherever you want them, for example:

- (void)viewDidLoad {
    [super viewDidLoad];
    lazyImage = [LazyInternet alloc];
    image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,50)];
    [self.view addSubview:image1];
    [lazyImage startDownload:@"yourdownloadURL" withDelegate:self withUnique:image1];

Once you have done this you just need to add in the receiving function in the same file. This is what is called after the file/code has been downloaded:

- (void)lazyInternetDidLoad:(NSData*)data withUnique:(id)unique {
    [unique setImage:[UIImage imageWithData:data]];

And that is all you need, you should now be able to use the app while your data downloads.

Hope this helps, any problems just leave a comment.