Tsukasa
Tsukasa

Reputation: 6562

Objective-C get list of files and subfolders in a directory

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

Upvotes: 26

Views: 37131

Answers (2)

trojanfoe
trojanfoe

Reputation: 122458

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]];
    }
}];

Upvotes: 46

Infinity James
Infinity James

Reputation: 4735

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.

Upvotes: 3

Related Questions