Checking if Image Exists in Bundle - iPhone

GuybrushThreepwood picture GuybrushThreepwood · Oct 28, 2011 · Viewed 13.7k times · Source

I have an app with a number of images. I want to check if an image exists in the bundle. If it does I display it, if not I display a replacement image.

The code below is what I've come up with, however it does not work. Can anyone spot what is wrong ?

Thank you !

NSString * photo = [NSString stringWithFormat:@"%d.jpg", UniqueID];    

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:photo];
if([fileManager fileExistsAtPath:path])
{

    [image setImage:[UIImage imageNamed:photo]];  
}

else {

    NSLog(@"Hello");

    [image setImage:[UIImage imageNamed:@"iPhoneHD.png"]];

}

EDIT - Changed following Simon's post below, however still not working correctly. Else statement always triggers.

Answer

Robin Summerhill picture Robin Summerhill · Oct 28, 2011

You are looking in your App's Documents directory. Is this really where you are expecting to find the images? If they are actually resources added to your bundle then you need to do this:

NSString *path = [[NSBundle mainBundle] pathForResource:uniqueID ofType:@"jpg"];

Easier still - just try loading the named image. If it fails then load the default:

UIImage *tempImage = [UIImage imageNamed:photo];

if (!tempImage) {
    tempImage = [UIImage imageNamed:@"iPhoneHD.jpg"]
}

[image setImage:tempImage];