views:

521

answers:

3

I am downloading images using the NSURLConnection sendSynchronousRequest method and that works fine. However, occasionally I run into an issue where the image URL points to something other than an image file. For example, I found this non-image URL was causing issues: http://www.100plusposters.com/images/ExoticFlowers.jpg The URL returns a Web page, which I assume occurs because the image is missing from the site.

One nice thing about Objective-C is that the invalid image doesn't cause a crash. It simply and quietly continues along and just doesn't display any image, but that is still a problem.

How can I validate the data returned to ensure it is a valid image file before displaying it?

Thanks!

My relevant code, in case that helps...

NSError *error = nil;
NSURLResponse *response;
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if(data != nil && [error localizedDescription] == nil) 
{
    //Create UIImage object using initWithData method
    //Display UIImage
}
+5  A: 

Looks like NSURLResponse object contains a MIMEType property. That should give you a pretty good idea what the type of the returned data is.

EightyEight
That works perfectly. Thank you!
Ken Pespisa
+1  A: 

Could we take this question one step further? What if the image data is incomplete or corrupt from the server? The complete transport works, the MIME type is image/jpeg, the UIImage is constructed and non-nil but the renderer discovers inconsistencies in the data and the log may show "Bad Huffman code" or "premature end of data segment"

How would I capture this error before tossing the UIImage into the view context and thereby getting a not-pretty image on the screen?

A: 

Hi,

I think by crosschecking the content length obtained from the header of the Http Request and finally recieved data would give you, whether the data downloaded was complete or not.

About the corrupt i dont have much info.

Pramod Jain