views:

14

answers:

1

Hi guys

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

+1  A: 

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:

  • Using NSURLConnection and it's delegate methods to download the image data, create an image object and update your UI when it's finished
  • Use blocks to wrap up your call to dataWithContentsOfURL: and dispatch it on an asynchronous queue
  • Perform this work on a separate thread (not recommended as the previous two options give you the same effect with less code).

All 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 the connection:didFailWithError: delegate method.

Jasarien
Ok, thanks, great answer, I already do it in a background tread, so I will use your advice)
Burjua