复制来自setImageWithURL的UIImageView

时间:2013-06-06 22:09:22

标签: ios image uiimageview

之前我通过使用两次从我的服务器拉出相同的图像,这工作正常,但我需要减少网络使用

NSString *friendAvatar = [NSString stringWithFormat:@"%@%@%@", @"http://www.mydomain.com/images/users/", myWords[0], @".jpg"];
[imageFile setImageWithURL:[NSURL URLWithString:friendAvatar]];
[bgImageFile setImageWithURL:[NSURL URLWithString:friendAvatar]]; //this is a zoomed in version of the friends photo

现在我正在使用这种方式来尝试拉出已经拉过照片的UIImageView的图像,这样我就不必两次拉同一张照片......

NSString *friendAvatar = [NSString stringWithFormat:@"%@%@%@", @"http://www.mydomain.com/images/users/", myWords[0], @".jpg"];
[imageFile setImageWithURL:[NSURL URLWithString:friendAvatar]];
[bgImageFile setImage:imageFile.image];

尝试使用我的新方法时。什么都没发生。调试器中没有错误,背景图片只是空白。

2 个答案:

答案 0 :(得分:1)

首先尝试创建UIImage,然后将UIImageView.image设置为创建的UIImage ...

UIImage *avatarImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:friendAvatar]]];

[imageFile setImage:avatarImage];
[bgImageFile setImage:avatarImage];

更好的方法是......

dispatch_queue_t myQueue = dispatch_queue_create("com.myProgram.myQueue", NULL);
dispatch_async(myQueue, ^{
    UIImage *avatarImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:friendAvatar]]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [imageFile setImage:avatarImage];
        [bgImageFile setImage:avatarImage];
    });
});

这将在后台线程上从Internet加载文件,然后在图像加载完成后更新主线程上的ImageViews。好处是您的应用程序在下载过程中不会冻结。

我希望有帮助

答案 1 :(得分:1)

根据您的评论我发现,因为您在致电时使用AFNetworking

[imageFile setImageWithURL:[NSURL URLWithString:friendAvatar]];

它正在后台线程上执行,但是下一行

[bgImageFile setImage:imageFile.image];

不是AFNetworking调用,所以它在前一行完成之前执行,因此没有imageFile.image可以使用...

所以,是的,我之前的回答要求你自己做异步代码,或者你可以在设置bgImageFile.image之前等待图像加载(这可能是用KVO完成的)