Skip to content

Instantly share code, notes, and snippets.

@XueshiQiao
Last active December 19, 2015 06:09
Show Gist options
  • Save XueshiQiao/5909516 to your computer and use it in GitHub Desktop.
Save XueshiQiao/5909516 to your computer and use it in GitHub Desktop.
UIImage From URL – Simplified (Using Blocks)
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!");
});
@XueshiQiao
Copy link
Author

It comes from Here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment