我目前正在开发的 iPhone 应用程序适用于 iOS >= 14.0 应用程序记录的很大一部分使用 AppDelegate 中的以下命令共享到公共 iCloud 容器:
lazy var persistentContainerPublic: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "PublicModel")
guard let description = container.persistentStoreDescriptions.first else {
print("Can't get description")
fatalError("\(#function): ERROR")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) // https://developer.apple.com/videos/play/wwdc2020/10650
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) // https://developer.apple.com/videos/play/wwdc2020/10650
description.cloudKitContainerOptions?.databaseScope = .public
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
} else {
print("\(type(of: self)) - loadPersistentStores completed sucessful")
}
})
return container
}()
记录在几秒钟内同步到 iCloud 容器,但仅在启动时同步到物理设备,有时我使用以下代码获取新记录:
private var pullControl = UIRefreshControl()
pullControl.attributedTitle = NSAttributedString(string: "")
pullControl.addTarget(self, action: #selector(refreshListData(_:)), for: .valueChanged)
tableView.refreshControl = pullControl
@objc private func refreshListData(_ sender: Any) {
fetchDocuments() // fetch all records from core data
tableView.reloadData()
refreshPublicObjects()
self.pullControl.endRefreshing()
}
这是 refreshPublicObjects 函数:
func refreshPublicObjects () {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let persistentContainer = appDelegate?.persistentContainerPublic
persistentContainer?.viewContext.refreshAllObjects()
}
我是否缺少任何东西来及时从 iCloud 获取更新,而不仅仅是在启动时,甚至用户都没有刷新表格视图?