写在一台设备上的文件无法在另一台设备上打开

时间:2018-02-18 19:51:54

标签: ios swift file icloud

这个问题在五年前被问到没有解决方案,所以我假设它不是同一个问题。

我有一个应用程序可以将多个文件写入iCloud。我可以看到当前文件在iCloud.com以及我的Mac iCloud文件夹上更新,但我只在第二台设备上的Files文件夹中看到了存根文件(带有iCloud徽章的文件)。尝试读取文件的我的应用程序失败,未找到"文件"。如果我从文件应用程序打开文件强制它下载,然后运行我的应用程序,它会打开并正确读取文件。所以,我的问题是,我如何以编程方式强制下载文件。我尝试追加" .icloud"到文件名,仍显示为未找到。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

基本思路是检查文件是否可用。如果不是,请使用startDownloadingUbiquitousItem(at url: URL)要求文件开始下载。

此处提供了整个iCloud文档:https://developer.apple.com/library/content/documentation/General/Conceptual/iCloudDesignGuide/Chapters/DesigningForDocumentsIniCloud.html

<强>更新 请注意,这是一个示例代码解决方案,旨在描述基本概念。

let fileManager = FileManager.default
let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents", isDirectory: true)
let iCloudDocumentToCheckURL = iCloudDocumentsURL?.appendingPathComponent("whateverFileName", isDirectory: false)

guard let iCloudDocumentPath = iCloudDocumentsURL?.path else {
    return
}

if fileManager.fileExists(atPath: iCloudDocumentPath) {
    // Do something with the document
} else {
    do {
        try fileManager.startDownloadingUbiquitousItem(at: iCloudDocumentToCheckURL!)
        // Will start downloading the file
    } catch let error as NSError {
        print("Unresolved error \(error), \(error.userInfo)")
    }
}