首页 > 解决方案 > 从 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吗?

标签: swiftxcodeicloud

解决方案


推荐阅读