This method uses blocks so will run on iOS4 onwards:

This post is a simplified version of the previous submitted post: A simple COCOA Asynchronous image loader class to use in your iPhone app


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void UIImageFromURL( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) )
{
    dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
    {
        NSData * data = [[[NSData alloc] initWithContentsOfURL:URL] autorelease];
        UIImage * image = [[[UIImage alloc] initWithData:data] autorelease];
        dispatch_async( dispatch_get_main_queue(), ^(void){
            if( image != nil )
            {
                imageBlock( image );
            } else {
                errorBlock();
            }
        });
    });
}
 
// usage
 
UIImageFromURL( [NSURL URLWithString:@"image url here"], ^( UIImage * image )
{
    NSLog(@"%@",image);
}, ^(void){
    NSLog(@"%@",@"error!");
});

Enjoyed this post?

Subscribe to our RSS Feed or Follow us on twitter to keep up to date with the latest from iOS-Blog. Remember, Sharing is caring so please click one of the following options:

Tags: , ,