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
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:
NSURLConnectionand 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
NSURLConnectionmethod you will be able to check its failure reason by implementing theconnection:didFailWithError:delegate method.