2013-02-13 29 views
3

我想单击一个按钮开始下载图像,并在更新后将我的UIImageView更新为新图像。我的代码的问题是它只下载东西,而不是更新。它只会更新,如果我再次点击它。 我希望它在未来的某个时候更新图像,当图像下载时。我怎么做?如何使用块异步下载图像?

编辑:我找到了错误的代码,改变它有点帮助,它都可以工作。 还有另外一个问题 - 我怎么简化这段代码而不会把它弄乱?它看起来过度。

- (IBAction)getImage 
{ 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
    ^{ 
     NSURL *imageURL = [NSURL URLWithString:@"http://example.com/1.jpg"]; 
     __block NSData *imageData; 

     dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
      ^{ 
       imageData = [NSData dataWithContentsOfURL:imageURL]; 


       dispatch_sync(dispatch_get_main_queue(), ^{ 
              self.image = [UIImage imageWithData:imageData]; 
             }); 
            }); 


    }); 

    self.imageView.image = self.image; 
} 

回答

18

您正在设置imageView在图像完成下载之前,您需要将逻辑移动到块中。此外,您还没有理由在dispatch_async的范围内额外添加dispatch_sync

- (IBAction)getImage 
{ 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
    ^{ 
     NSURL *imageURL = [NSURL URLWithString:@"http://example.com/1.jpg"]; 
     NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 

     //This is your completion handler 
     dispatch_sync(dispatch_get_main_queue(), ^{ 
      //If self.image is atomic (not declared with nonatomic) 
      // you could have set it directly above 
      self.image = [UIImage imageWithData:imageData]; 

      //This needs to be set here now that the image is downloaded 
      // and you are back on the main thread 
      self.imageView.image = self.image; 

     }); 
    }); 

    //Any code placed outside of the block will likely 
    // be executed before the block finishes. 
} 
+0

嗨,我正在研究相同的代码。我需要知道如何访问此块内的自我,因为属性只能在getter/setter形式的块内部访问。在这里使用self.imageView.image会给你一个错误。请让我知道你是如何为这个imageView创建一个属性的。请参阅我的代码。 http://stackoverflow.com/questions/23890573/access-the-control-inside-the-synchronous-block-in-xcode-5-0-iphone – 2014-05-27 14:00:02

2

退房https://github.com/rs/SDWebImage

我用它来下载图像与进度通知的背景。它可以简单地添加到您的项目使用Cocoapods(http://cocoapods.org)。

在Cocoapods和GitHub上还有其他几种异步图像加载器,如果这对您不适用。

0

这是我一直在使用的,虽然它没有提供任何我认为常常有用的进展。这很简单。

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *image))completionBlock 
{ 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
           if (!error) 
           { 
            completionBlock(YES,data); 
            NSLog(@"downloaded FULL size %lu",(unsigned long)data.length); 
           } else{ 
            completionBlock(NO,nil); 
           } 
          }]; 
}