我正在使用此问题的略微更新的代码: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
}
}
所以这有时会起作用,但它确实不稳定,例如我们测试了以下情况:
这有时会奏效,有时也不会。有时查询不会更新。
我们还测试了以下场景:
startDownloadingUbiquitousItem
函数似乎没有抛出,即使iCloud中没有任何内容,因为我认为iCloud仍然没有同步本地文件或删除了本地数据,但它也无法正常下载......但状态未下载。也许用户不应该通过设置擦除内容?我想知道我的代码是否遗漏了可能发生的情况,或者这个API对开发人员来说真的不方便......
谢谢!
答案 0 :(得分:0)
可能我们要求在“主线程”中添加通知。
NotificationCenter.default.addObserver(self, selector: #selector(self.queryUpdate(notification:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: self.documentsQuery)