FileManager.default.fileExists 表示文档目录不存在

RP-*_*P-3 3 nsfilemanager ios swift

FileManager.default.contentsOfDirectory声称文档目录不存在,即使它显然存在。我在运行 iOS 12.1.2 的实际 iPhone SE 上使用 Swift 4.2

我正在downloads使用以下内容读取我的应用程序中目录的内容:

do {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let downloadedContents = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
    print(downloadedContents)
} catch {
    print("Error while enumerating contents: \(error.localizedDescription)")
}
Run Code Online (Sandbox Code Playgroud)

这将打印以下内容,告诉我文档目录中存在一个文件:

[file:///private/var/mobile/Containers/Data/Application/698F8D51-92AF-4BAB-A212-0A0982090550/Documents/example-file/]
Run Code Online (Sandbox Code Playgroud)

(下载应用程序内购买后,我将文件从缓存目录移到那里,但我认为这与此问题无关)。

稍后在我的代码中,我想检查文件是否已下载。我正在使用以下内容:

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = URL(fileURLWithPath: "example-file", relativeTo: documentsURL)
var isDir : ObjCBool = false
if FileManager.default.fileExists(atPath: path.standardizedFileURL.absoluteString, isDirectory: &isDir) {
    if isDir.boolValue {
        return true
    } else {
        return false // file exists but is not directory
    }
} else {
    return false // file does not exist at all
}
Run Code Online (Sandbox Code Playgroud)

但这总是返回 false,即使contentsOfDirectory表明它存在。

在调试时,我也尝试过:

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
po FileManager.default.fileExists(atPath: documentsURL.standardizedFileURL.absoluteString)
Run Code Online (Sandbox Code Playgroud)

但这也返回false。现在我很确定我只是fileExists错误地使用了这些方法。

谁能发现我做错了什么?

RP-*_*P-3 8

原来应该使用documentsURL.path, 而不是任何类型的 URL。

路径以 开头,/var/mobile...而 URL 以file:///var...

  • 你的意思是你需要使用 `path` 而不是 `absoluteString`。 (3认同)