25

What is the trick to get an array list of full file/folder paths from a given directory? I'm looking to search a given directory for files ending in .mp3 and need the full path name that includes the filename.

NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:Nil];

NSArray* mp3Files = [dirs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"]];

this only returns the file name not the path

Tsukasa
  • 6,342
  • 16
  • 64
  • 96

2 Answers2

44

It's probably best to enumerate the array using a block, which can be used to concatenate the path and the filename, testing for whatever file extension you want:

NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath
                                                                    error:NULL];
NSMutableArray *mp3Files = [[NSMutableArray alloc] init];
[dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *filename = (NSString *)obj;
    NSString *extension = [[filename pathExtension] lowercaseString];
    if ([extension isEqualToString:@"mp3"]) {
        [mp3Files addObject:[sourcePath stringByAppendingPathComponent:filename]];
    }
}];
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

To use a predicate on URLs I would do it this way:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension='.mp3'"];
NSArray *mp3Files = [directoryContents filteredArrayUsingPredicate:predicate];

This question may be a duplicate: Getting a list of files in a directory with a glob

There is also the NSDirectoryEnumerator object which is great for iterating through files in a directory.

Community
  • 1
  • 1
Infinity James
  • 4,667
  • 5
  • 23
  • 36