Fetch data from WatchOS CoreData for WatchOS 9 widget with an App Group

Ive added App Group entitlements to my Watch target and Watch Widget target to hopefully create a container both the CoreData for the Watch app and the Widget can draw from. I put the CoreData object in there for hopefully both the Watch App and WatchOS 9 widget to access.

let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my-company.my-app")!
let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
let description = NSPersistentStoreDescription(url: storeURL)
let container = NSPersistentContainer(name: "DataModel")
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { ... }

Following posts in StackExchange Its been working for iOS App and Widget. It works wonderfully for iOS apps and their widgets. Would this be identical for WatchOS apps and Widgets? However when I use the same implementation for WatchOS and Watch widgets it fails to fetch the data giving an error :

WidgetsExtension[75018:10584043] [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'MyContactCard' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?

'executeFetchRequest:error: A fetch request must have an entity.'

The exact same widget files works on iOS.

EDIT: IT STARTED WORKING after I posted this. My have just been an error with the Core data models or something. Just leave this here so others can know that it does work same as iOS widgets

  • I worked out why I've been getting this error with the Widget, I was trying to fetch directly from PersistenceController() eg. let myfetchedContactCards = try persistenceController().shared.managedObjectContext.fetch(fetchRequest) but when I changed to let persistenceController = PersistenceController.shared let myfetchedContactCards = try persistenceController.managedObjectContext.fetch(fetchRequest) It worked. Must have fully loaded the model. I was trying to access before it had loaded?

Add a Comment