0

In my app, I have an NSPersistentCloudKitContainer set up in the following way:

    let container: NSPersistentCloudKitContainer

    init() {
        self.container = NSPersistentCloudKitContainer(name: "Model")

        self.container.persistentStoreDescriptions[0].setOption(
            true as NSNumber,
            forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey
        }

        self.container.loadPersistentStores { (_, error) in
            guard error == nil else {
                print("error loading store: \(error.debugDescription)")
                return
            }
        }
        
        self.container.viewContext.automaticallyMergesChangesFromParent = true
    }

When I invoke a fetch request on the context of the container in my iOS target, it works as expected. However, when I perform the same fetch request in my Widget target, it returns an empty array result.

In my iOS target, I have Background Modes / Remote Notifications and iCloud / CloudKit capabilities. In my Widget target, I have the iCloud / CloudKit capability.

Not sure why it isn't working, so any help would be much appreciated, thanks!

Richard Robinson
  • 867
  • 1
  • 11
  • 38
  • 1
    On extensions the Bundle Path is different so you can't load PersistenStore in the same way. Look here https://www.avanderlee.com/swift/core-data-app-extension-data-sharing/ a way to use the same shared PersistenStore – Martino Bonfiglioli Sep 08 '20 at 11:59
  • @MartinoBonfiglioli that fixed it! Thanks! – Richard Robinson Sep 08 '20 at 17:46
  • 1
    @RichardRobinson Hi Richard, can you please answer your own question? I'm having a hard time with `persistentContainer.persistentStoreDescriptions `. Can you please post your Core Data stack? – Igor R. Sep 18 '20 at 12:37
  • @RichardRobinson [This answer](https://stackoverflow.com/a/64000524/8697793) might help you. – pawello2222 Sep 21 '20 at 22:54

0 Answers0