Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a NSData is valid for usage in UIImage

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];

I have a jpeg file, I can confirm that the URL content is gathered successfully, but when I try to put my image data into the UIImage my app fails. I wonder if there is any check for NSData to confirm it is usable for UIImage.

I also don't know what causes this failure, and how to prevent it. Any help would be appreciated.

like image 936
Bartu Avatar asked Jun 17 '12 15:06

Bartu


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage . Save this answer.

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

What is UIImage in swift?

An object that manages image data in your app.


2 Answers

As stated in the documentation imageWithData: returns nil if UIImage could not create an image from the data. The correct way to handle this at runtime is to provide a placeholder image when that method returns nil.

As for the diagnostic, first look at the console messages, they sometimes provide useful info. If not, your best luck is to dump the NSData to disk and compare the result to the file stored on the server. You sometimes get corrupted data, you sometimes just get an html error message where you were expecting jpeg binary data.

like image 140
cdelacroix Avatar answered Sep 28 '22 09:09

cdelacroix


You can use

 if ([UIImage imageWithData:yourNSData]) {
     // there was an image
 }
like image 36
Bobby Avatar answered Sep 28 '22 08:09

Bobby