如何在iOS中递归获取我的包中的所有资源路径? [英] How do I get all resource paths in my bundle recursively in iOS?

查看:219
本文介绍了如何在iOS中递归获取我的包中的所有资源路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序包中有一个解压缩文件夹。我需要获取txt类型的所有文件的资源路径。我一直在使用它,

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?

推荐答案

我使用@发布的代码工作了以重新作为起点。诀窍是使用NSDirectoryEnumerator,它将以递归方式执行此操作。这是我写的函数,如果有人需要它。

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,使用 NSURL


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
}

这篇关于如何在iOS中递归获取我的包中的所有资源路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆