【发布时间】:2023-03-12 05:34:01
【问题描述】:
我正在使用这个问题的稍微更新的代码:Method for downloading iCloud files? Very confusing?
这里是代码的摘录:
private func downloadUbiquitiousItem(atURL url: URL) -> Void {
do {
try FileManager.default.startDownloadingUbiquitousItem(at: url)
do {
let attributes = try url.resourceValues(forKeys: [URLResourceKey.ubiquitousItemDownloadingStatusKey])
if let status: URLUbiquitousItemDownloadingStatus = attributes.allValues[URLResourceKey.ubiquitousItemDownloadingStatusKey] as? URLUbiquitousItemDownloadingStatus {
if status == URLUbiquitousItemDownloadingStatus.current {
self.processDocument(withURL: url)
return
} else if status == URLUbiquitousItemDownloadingStatus.downloaded {
self.processDocument(withURL: url)
return
} else if status == URLUbiquitousItemDownloadingStatus.notDownloaded {
do {
//will go just fine, if it is unnecessary to download again
try FileManager.default.startDownloadingUbiquitousItem(at: url)
} catch {
return
}
}
}
} catch {
}
//only happens if the try does not fail
self.documentsQuery = NSMetadataQuery()
self.documentsQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
self.documentsQuery.valueListAttributes = [NSMetadataUbiquitousItemPercentDownloadedKey,NSMetadataUbiquitousItemDownloadingStatusKey]
self.documentsQuery.predicate = NSPredicate(format: "%K like 'backup.json'", argumentArray: [NSMetadataItemFSNameKey])
NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)
DispatchQueue.main.async {
if self.documentsQuery.start() {
if self.restoreHUD != nil {
self.restoreHUD.show(animated: true)
//timeout for restoring
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(30), execute: {
if self.restoreHUD != nil {
self.restoreHUD.hide(animated: true)
}
})
}
}
}
} catch {
//file does not exist in icloud most likely
}
}
所以这有时可行,但它确实不稳定,例如我们测试了以下情况:
- 备份到 iCloud
- 在 Settings -> iCloud -> Storage -> Manage Storage -> MyApp -> backup.json 中检查我们是否有有效的文档
- 强制首次启动,以便应用恢复 backup.json(也就是执行上面的代码)
这有时有效,有时无效。有时查询不会更新。
我们还测试了以下场景:
- 通过设置手动从 iCloud 中删除备份
- 卸载应用并重新安装以提供首次启动
-
startDownloadingUbiquitousItem函数似乎没有抛出,即使 iCloud 中没有任何内容,因为我认为 iCloud 仍然没有同步本地文件或删除本地数据,但它也没有正确下载......但是状态未下载。
也许用户不应该通过“设置”擦除这些东西?我想知道我的代码是否缺少可能发生的情况,或者这个 API 对开发人员来说真的很不方便......
谢谢!
【问题讨论】:
标签: swift icloud icloud-documents