Getting a list of files in the Resources folder - iOS

IphoneIosResources

Iphone Problem Overview


Let's say I have a folder in my "Resources" folder of my iPhone application called "Documents".

Is there a way that I can get an array or some type of list of all the files included in that folder at run time?

So, in code, it would look like:

NSMutableArray *myFiles = [...get a list of files in Resources/Documents...];

Is this possible?

Iphone Solutions


Solution 1 - Iphone

You can get the path to the Resources directory like this,

NSString * resourcePath = [[NSBundle mainBundle] resourcePath];

Then append the Documents to the path,

NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];

Then you can use any of the directory listing APIs of NSFileManager.

NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];

Note : When adding source folder into the bundle make sure you select "Create folder references for any added folders option when copying"

Solution 2 - Iphone

Swift

Updated for Swift 3

let docsPath = Bundle.main.resourcePath! + "/Resources"
let fileManager = FileManager.default

do {
    let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
} catch {
    print(error)
}

Further reading:

Solution 3 - Iphone

You can try this code also:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray * directoryContents =  [[NSFileManager defaultManager]
                      contentsOfDirectoryAtPath:documentsDirectory error:&error];

NSLog(@"directoryContents ====== %@",directoryContents);

Solution 4 - Iphone

Swift version:

    if let files = try? FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath ){
        for file in files {
            print(file)
        }
    }

Solution 5 - Iphone

Listing All Files In A Directory

     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
     NSArray *contents = [fileManager contentsOfDirectoryAtURL:bundleURL
                           includingPropertiesForKeys:@[]
                                              options:NSDirectoryEnumerationSkipsHiddenFiles
                                                error:nil];

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension ENDSWITH '.png'"];
     for (NSString *path in [contents filteredArrayUsingPredicate:predicate]) {
        // Enumerate each .png file in directory
     }

Recursively Enumerating Files In A Directory

      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
      NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
                                   includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                     options:NSDirectoryEnumerationSkipsHiddenFiles
                                                errorHandler:^BOOL(NSURL *url, NSError *error)
      {
         NSLog(@"[Error] %@ (%@)", error, url);
      }];

      NSMutableArray *mutableFileURLs = [NSMutableArray array];
      for (NSURL *fileURL in enumerator) {
      NSString *filename;
      [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];

      NSNumber *isDirectory;
      [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];

       // Skip directories with '_' prefix, for example
      if ([filename hasPrefix:@"_"] && [isDirectory boolValue]) {
         [enumerator skipDescendants];
         continue;
       }

      if (![isDirectory boolValue]) {
          [mutableFileURLs addObject:fileURL];
       }
     }

For more about NSFileManager its here

Solution 6 - Iphone

Swift 3 (and returning URLs)

let url = Bundle.main.resourceURL!
    do {
        let urls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys:[], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
    } catch {
        print(error)
    }

Solution 7 - Iphone

Swift 4:

If you have to do with subdirs "Relative to project" (blue folders) you could write:

func getAllPListFrom(_ subdir:String)->[URL]? {
    guard let fURL = Bundle.main.urls(forResourcesWithExtension: "plist", subdirectory: subdir) else { return nil }
    return fURL
}

Usage:

if let myURLs = getAllPListFrom("myPrivateFolder/Lists") {
   // your code..
}

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
QuestionCodeGuyView Question on Stackoverflow
Solution 1 - IphoneDeepak DanduproluView Answer on Stackoverflow
Solution 2 - IphoneSuragchView Answer on Stackoverflow
Solution 3 - IphoneneowinstonView Answer on Stackoverflow
Solution 4 - IphoneMatt FrearView Answer on Stackoverflow
Solution 5 - IphoneGovindView Answer on Stackoverflow
Solution 6 - IphonenarcoView Answer on Stackoverflow
Solution 7 - IphoneAlessandro OrnanoView Answer on Stackoverflow