Search code examples
iosnsfilemanager

return all file names inside a folder in IOS app


How can i read all files list or array inside a directory. This directory/folder is inside my IOS app I check the below code but it returning me null.

NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"mag1"];

NSArray *myArray=[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
NSLog(@"mag1 directory: %@",myArray);

here mag1 is my directory which contains some files. This mag1 is inside my app directory.


Solution

  • Get the top-level app bundle folder using [[NSBundle mainBundle] bundlePath]:

    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *directory = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"mag1"];
    
    NSArray *files=[fileMgr contentsOfDirectoryAtPath:directory error:&error];
    NSLog(@"mag1 directory: %@",files);