【问题标题】:"The folder 'Documents' doesn't exist" error in Swift [duplicate]Swift中的“文件夹'文档'不存在”错误[重复]
【发布时间】:2019-01-27 00:53:36
【问题描述】:

我正在尝试在 Swift 中获取文件夹中的文件列表,这是一个代码 sn-p:

let fileManager = FileManager.default
if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    print(dir.absoluteString)                // print 1

    do {
        let files = try fileManager.contentsOfDirectory(atPath: dir.absoluteString)
        print(files)                         // print 2
    } catch {
        print(error.localizedDescription)    // print 3
    }
}

然后打印“print 1”:

file:///Users/.../.../Documents/

然后“打印 3”打印:

文件夹“文档”不存在。

目前,该文件夹中保存了很多文件,至少我的default.realm文件在那里。为什么会这样?

【问题讨论】:

  • 你不想使用absoluteString。这不会返回格式正确的文件路径。见下面阿里的回答。

标签: ios swift


【解决方案1】:

您应该使用dir.path 将 URL 转换为文件路径:

let files = try fileManager.contentsOfDirectory(atPath: dir.path)

【讨论】:

  • 这是正确答案。你也可以使用contentsOfDirectory(at:includingPropertiesForKeys:options:),它接受一个URL而不是一个路径字符串。
猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2017-04-13
相关资源
最近更新 更多