ios awkard 图像加载(url 到 nsdata 到 uiimage 到 uiimageview)

标签 ios uiimageview uiimage nsdata nsurl

我需要你在这个问题上逗我一下。这有点伪代码,因为实际情况相当复杂。除非需要,否则我不会以这种方式加载图像。假设我需要。

NSURL *bgImageURL = [NSURL URLWithString:@"https://www.google.com/images/srpr/logo3w.png"];

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:bgImageURL]];

[self.anIBOutletOfUIImageView setImage:img];

但我崩溃了
-[__NSCFData _isResizable]: unrecognized selector sent to instance 0x9508c70

如何将 URL 中的图像加载到 NSData 中,然后将该 NSData 加载到 UIImage 中并将该 UIImage 设置为我的 UIImageView 的图像?

再一次,我意识到这听起来像是胡说八道,但由于我正在使用图像缓存系统,我必须这样做:(

最佳答案

我通常如何处理这种情况(未编译,未测试):

NSURL * url = [NSURL URLWithString:@"https://www.google.com/images/srpr/logo3w.png"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue currentQueue]
                       completionHandler:^(NSURLResponse * resp, NSData * data, NSError * error) {

    // No error handling - check `error` if you want to
    UIImage * img = [UIImage imageWithData:data];
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:img waitUntilDone:YES];

}];

这避免了调用 dataWithContentsOfURL: 所暗示的长时间运行的网络请求。 ,因此您的应用程序可以在为图像下载数据的同时继续在主线程上执行操作。

附带说明一下,您似乎遇到了与 this question 相同的错误。 ;您可能想要检查您是否没有遇到对象分配问题。

关于ios awkard 图像加载(url 到 nsdata 到 uiimage 到 uiimageview),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473673/

相关文章:

ios - 如何使用 Masonry DSL 更新约束?

iOS 10 - AVPlayer 在播放视频时显示黑屏

ios - 在 UIImageView 中更新图像时,UIImage 分配不会 swift 发生

android - 如何为Android选择正确的图像分辨率

ios - 使用 UIGraphicsImageRenderer 渲染全尺寸图像

ios - SceneKit 场景背景内容 UIImage 数组错误

ios - 自动布局/砌体中心多个 View

ios - 在swift中设置http方法时可以将字符串作为数据传递吗

objective-c - 带有背景图片的 UIScrollView

iphone - 带有 UIImageViews 的 UITableView 显示大型 UIImages - 滚动性能