正在注册以接收远程CloudKit更改的通知不起作用

问题描述 投票:0回答:1

我刚刚使用新的iOS 13 NSPersistentCloudKitContainer完成CoreData + CloudKit的设置。它可以很好地工作,因为我可以使用自动生成的CoreData类进行属性访问和本地存储,并且NSPersistentCloudKitContainer自动在设备之间同步更改。我遇到的问题是如何获得有关远程更改的通知。我已经检查了Apple文档,并声明您告诉NSPersistentCloudKitContainerNSPersistentStoreDescription您要它发送通知,然后将其他对象注册为该通知的观察者。我已完成此操作,并添加了一种测试方法来显示何时检测到远程更改。测试方法生成的警报永远不会生成,但是如果我终止了该应用程序并重新打开它,则更改将立即存在。因此,我认为远程更改已同步并集成到本地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];
}
ios core-data cloudkit nsnotificationcenter
1个回答
0
投票

[访问​​应用程序的持久性CloudKit容器以获取viewContext时,您需要将automaticallyMergesChangesFromParent属性设置为true

lazy var managedContext: NSManagedObjectContext = {
    self.storeContainer.viewContext.automaticallyMergesChangesFromParent = true
    return self.storeContainer.viewContext
}()

进行单行更改将使应用程序(NSFetchedResultsController支持)可以响应于远程数据更改而更新UI ...

© www.soinside.com 2019 - 2024. All rights reserved.