1

我有一个正在构建的应用程序,它工作正常,但我使用的图像源来自一个网站,当我切换回我的初始视图时,它需要相当长的时间才能加载。我的问题是有没有办法完成这项工作并让速度更快。这是我用来提取图像源的代码

////Loads UIImageView from URL
todaysWallpaper.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.inkdryercreative.com/daily/archive/mondays/images/062-mondays-960x640-A.jpg"]]];

任何帮助或推动正确方向。很快,图像也会每天都发生变化,因此对此的任何帮助/想法将不胜感激。

4

2 回答 2

2

这里的问题dataWithContentsOfURL:是在主线程上,所以当下载图像时它会阻塞你的 UI。

您必须异步下载它。为此,我个人使用了我在互联网上找到的一段很棒的代码:SDWebImage。它完全符合您的要求。

于 2012-05-16T10:14:55.583 回答
1

将 UIImage 创建包装在异步运行的块中(代码假定为 ARC),然后在主线程中调用您的回调

@implementation Foo
...
Foo* __weak weakSelf=self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:
                   [NSURL  URLWithString:@"http://www.inkdryercreative.com/..jpg"]]];
    dispatch_sync(dispatch_get_main_queue(),^ {
        //run in main thread
       [weakSelf handleDelayedImage:image];
    });
});

-(void)handleDelayedImage:(UIImage*)image
{
   todaysWallpaper.image=image;
}

weakSelf 技巧确保您的 Foo 类被正确清理,即使 URL 请求仍在运行

于 2013-07-30T18:02:06.783 回答