获取Resources文件夹中的文件列表 - iOS

Cod*_*Guy 83 iphone resources ios

假设我的iPhone应用程序的"Resources"文件夹中有一个名为"Documents"的文件夹.

有没有办法在运行时获取该文件夹中包含的所有文件的数组或某种类型的列表?

所以,在代码中,它看起来像:

NSMutableArray *myFiles = [...get a list of files in Resources/Documents...];
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Dee*_*olu 135

您可以Resources像这样获取目录的路径,

NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
Run Code Online (Sandbox Code Playgroud)

然后追加Documents到路径,

NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];
Run Code Online (Sandbox Code Playgroud)

然后你可以使用任何目录列表API NSFileManager.

NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
Run Code Online (Sandbox Code Playgroud)

注意:将源文件夹添加到捆绑包时,请确保选择"复制时为任何添加的文件夹创建文件夹引用"选项

  • 您是否在复制时选择"为任何添加的文件夹创建文件夹引用"选项? (4认同)
  • 有趣的。没有附加它就可以工作并找到所有内容(包括 Documents 文件夹)。但是有了那个附加,“directoryOfContents”数组为空 (2认同)

Sur*_*gch 26

迅速

针对Swift 3进行了更新

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

do {
    let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
} catch {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

  • 错误域=NSCocoaErrorDomain 代码=260 ““资源”文件夹不存在。UserInfo={NSFilePath=/var/containers/Bundle/Application/A367E139-1845-4FD6-9D7F-FCC7A64F0408/Robomed.app/Resources, NSUserStringVariant=( Folder ), NSUnderlyingError=0x1c4450140文件或目录"}} (4认同)

Win*_*ton 18

您也可以尝试以下代码:

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

NSLog(@"directoryContents ====== %@",directoryContents);
Run Code Online (Sandbox Code Playgroud)


Mat*_*ear 11

Swift版本:

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


iGo*_*iGo 6

列出目录中的所有文件

     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
     }
Run Code Online (Sandbox Code Playgroud)

递归枚举目录中的文件

      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];
       }
     }
Run Code Online (Sandbox Code Playgroud)

有关NSFileManager的更多信息,请点击此处

  • 如果延伸有".",它将无法工作.换句话说,这将起作用:[NSPredicate predicateWithFormat:@"pathExtension ENDSWITH'png'"]; (3认同)

Ale*_*ano 6

斯威夫特4:

如果您必须处理“相对于项目”的子目录(蓝色文件夹),您可以编写:

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

用法

if let myURLs = getAllPListFrom("myPrivateFolder/Lists") {
   // your code..
}
Run Code Online (Sandbox Code Playgroud)


nar*_*rco 5

Swift 3(和返回的 URL)

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