ios - 注册以接收远程 CloudKit 更改的通知不起作用
问题描述
我刚刚使用新的 iOS 13 完成了 CoreData+CloudKit 的设置NSPersistentCloudKitContainer
。它工作得非常好,因为我可以使用自动生成的 CoreData 类进行属性访问和本地存储,并NSPersistentCloudKitContainer
自动同步设备之间的更改。我遇到的问题是收到远程更改的通知。NSPersistentCloudKitContainer
我已经检查了 Apple 文档,这表明您告诉NSPersistentStoreDescription
您希望它发送通知,然后将其他对象注册为该通知的观察者。我已经这样做了,并添加了一个测试方法来显示何时检测到远程更改。测试方法生成的警报永远不会生成,但如果我杀死应用程序并重新打开它,更改会立即出现。所以我相信远程更改正在同步并集成到本地 CoreData 存储中,但通知不起作用。我已将Background Modes
权利添加到我的目标并选择了Remote notification
模式。代码如下。任何帮助将不胜感激!
设置发送通知的选项:
- (NSPersistentCloudKitContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"<redacted>"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// ...
}
else {
// ...
[storeDescription setOption:@(YES) forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey];
// ...
}
}];
}
}
return _persistentContainer;
}
注册接收通知:
- (void)viewDidLoad {
[super viewDidLoad];
// ...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changes) name:NSPersistentStoreRemoteChangeNotification object:[CoreDataFunctions persistentContainer]];
}
响应变化的测试方法:
- (void)changes {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Changes received" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
解决方案
您观察到的是持久化容器而不是存储协调器,它应该是这样的:
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(persistentStoreRemoteChangeNotification:) name:NSPersistentStoreRemoteChangeNotification object:_persistentContainer.persistentStoreCoordinator];
推荐阅读
- opengl - 如何在多个窗口 SFML 和 GLFW 中渲染和获取输入?
- kubernetes - 同集群创建一批Pod,部分Pod启动时间超过40s
- docker - Docker 容器如何解决我的机器上不再工作
- javascript - 检测深度嵌套对象中的更改以使用 Angular 从服务中修改 NgStyle
- python - 用于 N 维 ODE 系统的四阶 Runge-Kutta 积分器的索引列表超出范围错误
- arrays - 数组内的Laravel vue SUM数组数据
- python - 如何修复“IndentationError:预期缩进块”
- javascript - 表单在按下按钮之前发布
- javascript - 由于 mime 类型“text/html”而不是“text/css”,样式表无法加载
- snowflake-cloud-data-platform - 雪花私有链接的 DNS 设置