FileManager.default.fileExists说文档目录不存在

时间:2019-01-15 02:06:57

标签: ios swift nsfilemanager

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

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

[file:///private/var/mobile/Containers/Data/Application/698F8D51-92AF-4BAB-A212-0A0982090550/Documents/example-file/]

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

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

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
}

但是,即使contentsOfDirectory显示它存在,它也总是返回false。

在调试时,我也尝试过:

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

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

有人可以发现我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

结果是应该使用documentsURL.path而不是任何URL。

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