UIImageFromURL

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

你可能感兴趣的:(UIImageFromURL)