Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if Image Exists in Bundle - iPhone

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.

like image 224
GuybrushThreepwood Avatar asked Oct 28 '11 15:10

GuybrushThreepwood


2 Answers

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];
like image 158
Robin Summerhill Avatar answered Oct 09 '22 16:10

Robin Summerhill


+(BOOL) fileExistsInProject:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fileInResourcesFolder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    return [fileManager fileExistsAtPath:fileInResourcesFolder];
}

is my answer.


returns YES if file is exist in bundle.you dont have to do anything with path. just say [fileExistsInProject:@"blabla.ext"]
like image 45
Zen Of Kursat Avatar answered Oct 09 '22 16:10

Zen Of Kursat