5

我想单击一个按钮开始下载图像并在更新后将我的 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;
}
4

3 回答 3

22

您正在设置imageView图像下载完成之前,您需要将逻辑移动到块中。您也没有理由dispatch_syncdispatch_async.

- (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.
}
于 2013-02-13T19:26:31.657 回答
2

查看https://github.com/rs/SDWebImage

我用它在后台下载带有进度通知的图像。可以使用 Cocoapods ( http://cocoapods.org ) 将它简单地添加到您的项目中。

Cocoapods 和 GitHub 上还有其他几个异步图像加载器可用,如果它们不适合你的话。

于 2013-02-13T19:30:36.587 回答
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);
                               }
                           }];
}
于 2015-02-10T20:36:01.150 回答