How can you determine if a file exists within the app bundle?

IphoneNsbundle

Iphone Problem Overview


Sorry, dumb question number 2 today. Is it possible to determine if a file is contained within the App Bundle? I can access files no problem, i.e.,

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];

But can't figure out how to check if the file exists there in the first place.

Regards

Dave

Iphone Solutions


Solution 1 - Iphone

[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];

Solution 2 - Iphone

This code worked for me...

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName])
{
    NSLog(@"File exists in BUNDLE");
}
else
{
    NSLog(@"File not found");
}

Hopefully, it will help somebody...

Solution 3 - Iphone

pathForResource will return nil if the resource does not exist. Checking again with NSFileManager is redundant.

Obj-C:

 if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {                                              
      NSLog(@"The path could not be created.");
      return;
 }

Swift 5:

 guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
      print("The path could not be created.")
      return
 }

Solution 4 - Iphone

NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
	if(![fileManager fileExistsAtPath:path])
	{
		// do something
	}

Solution 5 - Iphone

Same as @Arkady, but with Swift 2.0:

First, call a method on mainBundle() to help create a path to the resource:

guard let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "txt") else {
    NSLog("The path could not be created.")
    return
}

Then, call a method on defaultManager() to check whether the file exists:

if NSFileManager.defaultManager().fileExistsAtPath(path) {
    NSLog("The file exists!")
} else {
    NSLog("Better luck next time...")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMagic Bullet DaveView Question on Stackoverflow
Solution 1 - IphoneRob NapierView Answer on Stackoverflow
Solution 2 - IphoneArkadyView Answer on Stackoverflow
Solution 3 - IphoneDavid CrowView Answer on Stackoverflow
Solution 4 - IphoneIggyView Answer on Stackoverflow
Solution 5 - Iphonesudo make installView Answer on Stackoverflow