我有一个图像的 URL(从 UIImagePickerController 获取)但我不再在内存中有该图像(该 URL 是从应用程序的前一次运行中保存的)。我可以再次从 URL 重新加载 UIImage 吗?
我看到 UIImage 有一个 imageWithContentsOfFile: 但我有一个 URL。我可以使用 NSData 的 dataWithContentsOfURL: 读取 URL 吗?
编辑1
根据@Daniel 的回答,我尝试了以下代码,但它不起作用...
NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL);
if (photoURL) {
NSURL* aURL = [NSURL URLWithString:photoURL];
NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
self.photoImage = [UIImage imageWithData:data];
[data release];
}
当我运行它时,控制台显示:
-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'
查看调用堆栈,我正在调用 URLWithString,它调用 URLWithString:relativeToURL:,然后是 initWithString:relativeToURL:,然后是 _CFStringIsLegalURLString,然后是 CFStringGetLength,然后是 forwarding_prep_0,然后是 forwarding,然后 -[NSObject doesNotRecognizeSelector]。
知道为什么我的 NSString(photoURL 的地址是 0x536fbe0)不响应长度吗?为什么它说它不响应-[NSURL 长度]?它不知道 param 是一个 NSString,而不是一个 NSURL 吗?
编辑2
好的,代码的唯一问题是字符串到 URL 的转换。如果我对字符串进行硬编码,其他一切都可以正常工作。所以我的 NSString 有问题,如果我无法弄清楚,我想这应该作为一个不同的问题提出来。插入这一行(我从上面的控制台日志粘贴路径),它工作正常:
photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";
最佳答案
您可以这样做(同步但紧凑):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
更好的方法是使用 Apple 的 LazyTableImages 来保持交互性。
关于ios - 我可以从 URL 加载 UIImage 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2782454/