swift - 从 iCloud 下载文件的正确方法
问题描述
我一直在尝试在我的应用程序中实现 iCloud 备份功能。一些 Stack Overflow 答案和其他网站说以下方法可行。但是,以下代码有时不起作用。下载进度要么固定为 0%,要么显示为 100%,但文件仍然是过时的本地副本。
func download(itemUrl: URL) {
// Remove the local copy of the item
try? FileManager.default.evictUbiquitousItem(at: itemUrl)
// Request iCloud to start downloading the item
try? FileManager.default.startDownloadingUbiquitousItem(at: itemUrl)
// Watch for item status change
// Create metadata query to observe:
// 1. The path of the file item
// 2. The download progress of the file item
let metadataQuery = NSMetadataQuery()
metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDataScope, NSMetadataQueryUbiquitousDocumentsScope]
metadataQuery.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "%K == %@", NSMetadataItemPathKey, itemUrl.path),
NSPredicate(format: "%K >= 0", NSMetadataUbiquitousItemPercentDownloadedKey)
])
// Called when the query result is updated
NotificationCenter.default.addObserver(forName: .NSMetadataQueryDidUpdate, object: metadataQuery, queue: nil, using: { notification in
self.updateDownloadProgress(notification)
})
// Called when the query is finished
NotificationCenter.default.addObserver(forName: .NSMetadataQueryDidFinishGathering, object: metadataQuery, queue: nil, using: { notification in
self.updateDownloadProgress(notification)
})
// Start the query
metadataQuery.start()
}
和updateDownloadProgress
功能:
func updateDownloadProgress(_ notification: Notification) {
// Get download progress (%),
// Stop the query when the progress reaches 100%
}
错误处理被省略。我假设 iCloud 中每分钟或每小时有一个请求限制,这阻止了此方法始终按我的意图工作。我应该进行哪些更改才能使这项工作 100% 完成?任何帮助将不胜感激。
更新:这个问题与我没有使用的事实有关NSFileCoordinator
吗?
解决方案
推荐阅读
- python - 在多个 GPU 上运行detectron2 训练
- react-native - 更改全局状态时如何知道渲染结束
- caching - 以缓存为代价消耗 Linux 机器上的“空闲”内存
- java - java - 如何使用java spring boot通知pod中容器内的事件
- networking - 如何配置两个域以使用相同的 SSL 证书?
- react-native - ReactNative:显示来自本地存储的图像不起作用
- python - 在python中将天数转换为日期
- powerbi - 如何根据 Power BI 中的另一列计算一个值在列表中出现的次数?
- javascript - JS隐藏其他表时如何显示第二个表
- reactjs - 在 axios.post 之外访问 axios 响应