【问题标题】:How to filter file with extension from document directory in iOS?如何从iOS中的文档目录过滤扩展名文件?
【发布时间】:2013-07-24 02:05:57
【问题描述】:

您好,我现在正在从 iOS 的文档目录中检索文件。

我还按 CreationDate 对文件进行了排序。

在我的文档目录中,还有很多文件夹和文件。

因此,当我从文档目录中检索所有文件时,该文件夹名称也包括在内。

我只想检索 (.txt) 格式的文件。

我该怎么做?

【问题讨论】:

    标签: ios cocoa-touch nsfilemanager


    【解决方案1】:

    这是对@Wain 的回答的补充,并假设您正在使用 webview 加载文本文件

      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];
      NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.txt'"];
      filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
      NSLog(@"files array %@", filePathsArray);
      NSString *localDocumentsDirectoryVideoFilePath = [documentsDirectory
                                                        stringByAppendingPathComponent:[filePathsArray objectAtIndex:0]];
      NSURL *fileUrl=[NSURL fileURLWithPath:
                       localDocumentsDirectoryVideoFilePath];
      [_webview loadRequest:[NSURLRequest requestWithURL:fileUrl]];
    

    这里的 _webview 是一个 IBOutlet。此外,它正在加载第一个文本文件。
    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      假设所有文件都有扩展名,您可以创建一个谓词并使用它来过滤数组。谓词的格式如下:

      @"self ENDSWITH '.txt'"
      

      根据您在下面的评论,您实际上拥有完整的文件NSURL,而不是字符串文件名。所以你应该使用谓词格式:

      @"absoluteString ENDSWITH '.txt'"
      

      【讨论】:

      • 是的。但是我也按 creationDate 排序,不能用它过滤。有什么办法吗?
      • 排序和过滤无关。你是如何排序的,你发现了什么问题?
      • 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“不能对不是字符串的内容进行子字符串操作(lhs = file://localhost/private/var/mobile /Applications/C72F3F4C-EBF0-4A74-879B-3219C7147479/Documents/Temp/rhs = .txt)'
      • @Yahiko,你可能需要convert the NSURL to a NSString。您不能在 NSURL 上调用 NSString 函数。
      • @MarcusAdams,您可以,或者使用谓词从 URL 中获取 absoluteString
      猜你喜欢
      • 2020-11-01
      • 2013-01-28
      • 2010-10-07
      • 2019-05-22
      • 2014-09-26
      • 2011-01-24
      • 2020-12-15
      • 1970-01-01
      • 2010-12-31
      相关资源
      最近更新 更多