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

Jac*_*nkr 1 nsurl uiimageview uiimage nsdata ios

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

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

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

[self.anIBOutletOfUIImageView setImage:img];
Run Code Online (Sandbox Code Playgroud)

但我崩溃了

-[__NSCFData _isResizable]: unrecognized selector sent to instance 0x9508c70
Run Code Online (Sandbox Code Playgroud)

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

再次,我意识到这听起来像废话,但由于图像缓存系统我正在使用我必须这样做:(

Tim*_*Tim 5

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

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];

}];
Run Code Online (Sandbox Code Playgroud)

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

作为旁注,你似乎遇到了与这个问题相同的错误; 您可能想要检查您是否遇到了对象分配问题.