How to determine if a file exists in the application bundle?

Sorry, dumb question # 2 today. Can I determine if a file is contained in a Bundle application? I can access files without problems, i.e.,

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

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

Hello

Dave

+48
iphone nsbundle
Jan 07
source share
5 answers
 [[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName]; 
+68
Jan 07
source share

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"); } 

Hope this helps someone ...

+15
Dec 15 '13 at 6:54
source share
 NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"]; if(![fileManager fileExistsAtPath:path]) { // do something } 
+3
Mar 19 '10 at 15:57
source share

pathForResource will return zero 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 4:

  guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else { print("The path could not be created.") return } 
+2
Feb 24 '16 at 18:46
source share

Same as @Arkady, but with Swift 2.0:

First call the mainBundle() method to create the path to the resource:

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

Then call the method on defaultManager() to check if the file exists:

 if NSFileManager.defaultManager().fileExistsAtPath(path) { NSLog("The file exists!") } else { NSLog("Better luck next time...") } 
+1
Jul 25 '15 at 10:52
source share



All Articles