如何检查 iPhone 中是否使用 dataWithContentsOfURL 加载了图像?
在我的 iPhone 应用程序中,我使用以下代码行加载图像:
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
如何检查是否已加载图像?我的意思是有时它不会给出任何错误,但我有空白而不是图像。我想检查它是否已完全加载,如果没有,请尝试重做一次。
谢谢
In my iPhone app I'm loading images using this line of code:
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
How can I check if I have image loaded? I mean sometimes it doesn't give any error, but I have blank white space instead of image. I want to check if it was completely loaded and if not, try to do it again.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请注意
dataWithContentsOfURL:
是一个阻塞 API,如果在主线程上使用,将导致您的应用程序挂起直至完成。如果您在 3G 或 EDGE 等慢速连接上使用此代码,您的应用程序将在图像加载之前显示为无响应 - 您不希望出现这种情况。您应该考虑以下选项之一:
NSURLConnection
及其委托方法来下载图像数据、创建图像对象并在完成后更新您的 UIdataWithContentsOfURL:
并将其分派到异步队列上不过,这一切都是为了另一个问题。至于您的实际问题,您可以检查返回的数据对象是否有效。文档指出,如果无法创建数据对象,则此方法返回 nil。
如果您想知道失败的原因,您应该使用 dataWithContentsOfURL:options:error: 并传递一个错误指针,您可以在失败时检查该错误指针。
但是,正如我所说,如果您使用
NSURLConnection
方法,您将能够通过实现connection:didFailWithError:
委托方法来检查其失败原因。First of all, be aware that
dataWithContentsOfURL:
is a blocking API and, if used on the main thread, will cause your app to hang until it completes. If you're using this code on a slow connection such as 3G or EDGE, your app will appear to be unresponsive until the image loads - you don't want that.You should instead consider one of the following options:
NSURLConnection
and it's delegate methods to download the image data, create an image object and update your UI when it's finisheddataWithContentsOfURL:
and dispatch it on an asynchronous queueAll that is for another question though. As for your actual question you can check whether the returned data object is valid. The docs state that this method returns nil if the data object could not be created.
If you want to know the reason why it failed, you should use
dataWithContentsOfURL:options:error:
and pass an error pointer which you can check when it fails.However, as I said, if you use the
NSURLConnection
method you will be able to check its failure reason by implementing theconnection:didFailWithError:
delegate method.