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

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

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

[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
}

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

在调试的时候,我也尝试过:

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

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

任何人都可以发现我做错了什么吗?

最佳答案

原来应该使用 documentsURL.path,而不是任何一种 URL。

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

关于ios - FileManager.default.fileExists 表示文档目录不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191807/

相关文章:

ios - 在 Swift 中转义字符串

iOS UITableView : what's the different between "cellForRowAtIndexPath" and "willDisplayCell: forRowAtIndexPath:"

swift - 创建 plist 并将其复制到文件夹 MacOS Swift

ios - 为什么 Apple 在使用 NSFileManagerDelegate 时建议使用自己的 NSFileManager?

iphone - 单元格中未显示 UITableViewCellAccessoryDe​​tailDisclosureButton

android - 如何在我的 flutter 应用程序中显示图像?我在做什么不工作

ios - 如何设置不是InterfaceController的HKWorkoutSessionDelegate

ios - 在方向被另一个(iOS)强制横向后,如何恢复 UIViewController 的正确方向?

ios - 合并两个 UIImages swift 4

ios - 从 iOS 中的子文件夹加载 iCloud 文档