对于 iCloud 中可能尚未下载的文件使用 NSFileManager.fileExists(atPath:) 是否安全?

Mar*_*ark 6 cocoa nsurl nsfilemanager icloud icloud-drive

我需要一种 100% 故障安全的方法来确定文件名/文件 URL 是否可用于将数据写入磁盘,而不会意外删除现有文件。

目前我正在使用NSFileManager.fileExists(atPath:),但我想知道,如果父目录位于 iCloud 中并且我的文件 URL 指向 iCloud 中尚未下载到设备的现有文件怎么办?

让我想到的是这两种方法URL

  • func checkResourceIsReachable() throws -> Bool
  • func checkPromisedItemIsReachable() throws -> Bool

资源和承诺项目之间存在区别。承诺项目定义为:

除非您使用文件协调器对其 URL 执行协调读取(这会导致内容被下载或以其他方式生成),否则无法保证承诺的项目的内容会存在于文件系统中。

背景:

我想要的是一个扩展,FileManager它返回给定(现有)文件 URL 的下一个可用的、不存在的文件名。例如:

  • 假设我现有的文档是:/documents/Text.txt
  • 下一个可用的文件名可能是:/documents/ Text 2 .txt

如何检查Text 2.txt本地和 iCloud 中是否确实不存在?

这是我目前的方法:

// Safer than: FileManager.default.fileExists(at: url) ?
private func fileExists(at url:URL) throws -> Bool
{
    if (try url.resourceValues(forKeys: [.isUbiquitousItemKey])).isUbiquitousItem == true
    {
        return try url.checkPromisedItemIsReachable()
    }
    else
    {
        return try url.checkResourceIsReachable()
    }
}
Run Code Online (Sandbox Code Playgroud)