Alex Rivera | Logout

How do I get all resource paths in my bundle recursively in iOS?

Asked 2011-04-29T19:36:44.167
21

I have an "unzipped" folder in my application bundle. I need to get the resource paths for all files of type txt. I've been using this,

NSArray *filePaths = [NSBundle pathsForResourcesOfType:@"txt" inDirectory:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/unzipped"]];

But it only gets files in the first directory. Is there a recursive version of this somewhere that I'm just missing?

Edit
Report

1 Answer

24

I got this working using the code posted by @rekle as a starting point. The trick is to use NSDirectoryEnumerator, which will do this recursively. Here's the function I wrote in case anyone needs it.

- (NSArray *)recursivePathsForResourcesOfType:(NSString *)type inDirectory:(NSString *)directoryPath{

    NSMutableArray *filePaths = [[NSMutableArray alloc] init];

    // Enumerators are recursive
    NSDirectoryEnumerator *enumerator = [[[NSFileManager defaultManager] enumeratorAtPath:directoryPath] retain];

    NSString *filePath;

    while ((filePath = [enumerator nextObject]) != nil){

        // If we have the right type of file, add it to the list
        // Make sure to prepend the directory path
        if([[filePath pathExtension] isEqualToString:type]){
            [filePaths addObject:[directoryPath stringByAppendingPathComponent:filePath]];
        }
    }

    [enumerator release];

    return [filePaths autorelease];
}

Swift, using NSURL

func recursivePathsForResources(type type: String) -> [NSURL] {

    // Enumerators are recursive
    let enumerator = NSFileManager.defaultManager().enumeratorAtPath(bundlePath)
    var filePaths = [NSURL]()

    while let filePath = enumerator?.nextObject() as? String {

        if NSURL(fileURLWithPath: filePath).pathExtension == type {
            filePaths.append(bundleURL.URLByAppendingPathComponent(filePath))
        }
    }

    return filePaths
}
answered 2011-05-02T17:01:15.593

Your Answer