【问题标题】:Getting a list of files in the Resources folder - iOS获取资源文件夹中的文件列表 - iOS
【发布时间】:2011-09-17 22:36:27
【问题描述】:

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

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

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

NSMutableArray *myFiles = [...get a list of files in Resources/Documents...];

这可能吗?

【问题讨论】:

    标签: iphone ios resources


    【解决方案1】:

    斯威夫特 4:

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

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

    用法

    if let myURLs = getAllPListFrom("myPrivateFolder/Lists") {
       // your code..
    }
    

    【讨论】:

    • 正是我想要的。谢谢!!
    【解决方案2】:

    Swift 版本:

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

    【讨论】:

      【解决方案3】:

      斯威夫特

      为 Swift 3 更新

      let docsPath = Bundle.main.resourcePath! + "/Resources"
      let fileManager = FileManager.default
      
      do {
          let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
      } catch {
          print(error)
      }
      

      进一步阅读:

      【讨论】:

      • Error Domain=NSCocoaErrorDomain Code=260 “文件夹“资源”不存在。” UserInfo={NSFilePath=/var/containers/Bundle/Application/A367E139-1845-4FD6-9D7F-FCC7A64F0408/Robomed.app/Resources, NSUserStringVariant=( 文件夹), NSUnderlyingError=0x1c4450140 {Error Domain=NSPOSIXErrorDomain Code=2 "没有这样的文件或目录"}}
      • 我刚刚删除了 + "/Resources" 并得到了一些东西。我不确定如何处理我返回的数组中的值。
      • 亲爱的读者,我目前没有更新我的 iOS 答案。不过,这似乎是其中之一,可以使用一些更新。如果您解决了上面 cmets 中写的问题,请随时编辑我的答案并更正它。
      【解决方案4】:

      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)
          }
      

      【讨论】:

        【解决方案5】:

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

        NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
        

        然后将Documents追加到路径中,

        NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];
        

        然后您可以使用NSFileManager 的任何目录列表API。

        NSError * error;
        NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
        

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

        【讨论】:

        • 有趣。没有附加它就可以工作并找到所有内容(包括 Documents 文件夹)。但有了那个附加,“directoryOfContents”数组为空
        • 哦,等等,“文档”是“组”而不是文件夹。嗯。如何在资源文件夹中添加文件夹?
        • 您可以将Drag & Drop 一个文件夹放到项目中,内容将被复制过来。 添加Copy Files构建阶段并指定要在其中复制的目录。
        • 好的,我把它拖进去了。但它仍然认为目录是空的。嗯。
        • 复制时是否选择了Create folder references for any added folders选项?
        【解决方案6】:

        你也可以试试这个代码:

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

        【讨论】:

        • 您在 directoryContents 中分配一个数组,该数组立即被 contentOfDir 返回的数组覆盖...
        • 我想要展示的只是一个包含目录内容的数组。该数组只是为了举例。我稍微修改了一下。
        【解决方案7】:

        列出目录中的所有文件

             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
             }
        

        递归枚举目录中的文件

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

        有关 NSFileManager 的更多信息,请参阅here

        【讨论】:

        • 如果扩展名有'.',它将不起作用。换句话说,这将起作用: [NSPredicate predicateWithFormat:@"pathExtension ENDSWITH 'png'"];
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-06
        • 2011-12-18
        • 2023-03-24
        • 1970-01-01
        • 2010-12-02
        • 2014-07-12
        相关资源
        最近更新 更多