Wednesday, November 21, 2012

UIImage From URL – Simplified (Using Blocks)


This post is a simplified version of the previous submitted post: A simple COCOA Asynchronous image loader class to use in your iPhone app
This method uses blocks so will run on iOS4 onwards:








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!");
});

No comments: