首页 > 解决方案 > 注册以接收远程 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];
}

标签: ioscore-datacloudkitnsnotificationcenter

解决方案


您观察到的是持久化容器而不是存储协调器,它应该是这样的:

[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(persistentStoreRemoteChangeNotification:) name:NSPersistentStoreRemoteChangeNotification object:_persistentContainer.persistentStoreCoordinator];

推荐阅读