【问题标题】:How do I get an array of file names from the iOS File Manager如何从 iOS 文件管理器中获取文件名数组
【发布时间】:2018-12-31 19:01:46
【问题描述】:

我正在创建一个录音应用程序,并声明了一个空数组来存储所有文件的名称。

var recordingTitles: [String] = []

当我启动应用程序时,我有一个函数可以检查文件管理器中已经存储了哪些文件并返回文件数量,以便在 collectionView 中显示正确数量的单元格。

override func viewDidLoad() {
    super.viewDidLoad()
    getNumberOfRecordings()

}

// Get number of actual recording files stored in the File Manager Directory
func getNumberOfRecordings() {
    let directoryUrl = getDirectory()

    do {
        contentsOfFileManager = try myFileManager.contentsOfDirectory(at: directoryUrl, includingPropertiesForKeys: [URLResourceKey(rawValue: recordingsKey)], options: .skipsHiddenFiles)

    } catch let error {
        print(error.localizedDescription)
    }
    numberOfRecordings = contentsOfFileManager.count
}

我想获取文件的名称并将它们分配给“recordingTitles”数组,以便为​​每个单元格显示正确的标题。我已经尝试阅读File Manager 的 Apple 文档,但还没有找到解决方案。提前感谢您的帮助!

【问题讨论】:

  • 你现在得到什么输出?一个空列表?出错了?
  • 感谢您的帮助@skylerl。 recordingTitles 数组一开始是空的,因此当应用程序尝试根据文件管理器目录中当前的文件数加载标题时,我得到一个“索引超出范围”。我的 getNumberOfRecordings() 函数经历了从文件管理器获取 URL 数组的过程,但我不确定如何仅获取文件名并将它们转换为字符串数组以分配给 recordingTitles

标签: arrays swift nsfilemanager


【解决方案1】:

所以,contentsOfFileManager 将由 NSURL 对象组成。这些对象具有不同的字段,您可以从中提取和使用。看起来您只对文件名感兴趣,所以我想提请您注意 NSURL 的 lastPathComponent 字段。来自文档:

此属性包含最后一个路径组件,使用 replacePercentEscapes(using:) 方法未转义。例如,在 URL file:///path/to/file 中,最后一个路径组件是 file。

换句话说,调用myNsurl.lastPathComponent 应该会为您提供文件名。因此,您可以遍历 myFileManager.contentsOfDirectory 返回的数组并获取每个数组的 lastPathComponent 并将它们添加到另一个仅包含文件名的数组中。

【讨论】:

    【解决方案2】:

    使用map 函数。你可能想要这样的东西:

    recordingTitles = try myFileManager.contentsOfDirectory(at:directoryURL, 
        includingPropertiesForKeys: nil).map {$0.lastPathComponent}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2021-07-26
      • 2017-06-12
      相关资源
      最近更新 更多