I am working on IOS 14 widget. I want to display core data on the widget, but unable to access the data.
How can i access the core app data from within the widget.
Code Block swift let container: NSPersistentContainer = { let pc = NSPersistentContainer(name: "Model") let storeURL = URL.storeURL(for: "group.hourglass", databaseName: "group.hourglass") let storeDescription = NSPersistentStoreDescription(url: storeURL) pc.persistentStoreDescriptions = [storeDescription] pc.loadPersistentStores { _, error in if let error = error { fatalError(error.localizedDescription) } } return pc }()
Code Block swift public extension URL { static func storeURL(for appGroup: String, databaseName: String) -> URL { guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { fatalError("Shared file container could not be created.") } return fileContainer.appendingPathComponent("\(databaseName).sqlite") } }
Code Block @main struct RunRosterApp: App { @Environment(\.scenePhase) private var scenePhase @StateObject private var persistentStore = PersistentStore.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistentStore.context) } }
Code Block @main struct WidgetRunPlanner: Widget { @StateObject private var persistentStore = PersistentStore.shared private let kind: String = "WidgetRunPlanner" public var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in WidgetRunPlannerEntryView(entry: entry) .environment(\.managedObjectContext, persistentStore.context) } }
If you have any experience with this any help is greatly appreciated. The Target Membership checkbox's have been appropriately checked.Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'RunEvents''
Problem:
Since app extensions run as part of a host application rather than as part of their containing app (i.e. your app’s extensions run in somebody else’s app), data sharing isn’t automatic.
Solution:
The preferred way is to track changes (History Tracking) in the app's entities and update into widget's entities. Refer: https://developer.apple.com/documentation/coredata/consuming_relevant_store_changes
Approach:
1.0 - Create App Groups
2.1 - Create separete app entities and widget entities
2.2 - Create separate configurations for app entities and widget entities
2.3 - Assign them configuration to their entities
3.0 - Use app group while creating and loading the container
4.0 - Use history tracking to track changes from the app's entities and update into widget's entites.