NSError *error = nil;
NSURL *url = [NSURL URLWithString:[imageLinks objectAtIndex:0]];
NSData *tdata = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
}else {
// no error, this one is being called within my app
NSLog(@"Data loaded successfully");
}
self.pictureView1.image = [UIImage imageWithData:tdata];
我有一个 jpeg 文件,我可以确认 URL 内容已成功收集,但是当我尝试将我的图像数据放入 UIImage
时,我的应用程序失败了。我想知道是否有任何检查 NSData 以确认它可用于 UIImage
。
我也不知道是什么原因导致了这种失败,以及如何预防。任何帮助将不胜感激。
最佳答案
如前所述in the documentation imageWithData:如果 UIImage 无法从数据创建图像,则返回 nil。在运行时处理此问题的正确方法是在该方法返回 nil 时提供占位符图像。
至于诊断,首先查看控制台消息,它们有时会提供有用的信息。如果没有,最好的运气是将 NSData 转储到磁盘并将结果与存储在服务器上的文件进行比较。您有时会得到损坏的数据,有时您只是在您期望 jpeg 二进制数据的地方收到一条 html 错误消息。
关于ios - 如何检查 NSData 在 UIImage 中的使用是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11072613/