6

I have an app that uses Core Data + CloudKit stack. (Core Data syncs between devices.). Now I want to display data from Core Data in iOS 14 widget (view in WidgetKit target).

My goal is to have data in widget also be actual data from Core Data: i.e. — user changed record on device A, and little later on device B (with widget) changes represented in widget.

How should I do it:

a) Add App Group capability for main app target and widget target; and fetch Core Data in widget target.
b) Fetch Core Data in main app target, save to file (plist?, JSON?) and later use that file in widget.
c) Fetch Core Data in main app target, get that data from widget target. (Is it possible?)

What is the most reasonable way? Thanks for any suggestions.

Igor R.
  • 399
  • 4
  • 23
  • You can easily use the same Core Data container for the App and the Widget. See [Fetch data from CoreData for iOS 14 widget](https://stackoverflow.com/questions/63936425/fetch-data-from-coredata-for-ios-14-widget) or [Share data between main App and Widget in SwiftUI for iOS 14](https://stackoverflow.com/questions/63922032/share-data-between-main-app-and-widget-in-swiftui-for-ios-14) – pawello2222 Sep 18 '20 at 09:42
  • @pawello2222 ty for your comment. I get message "Context in environment is not connected to a persistent store coordinator" at the [line 32, gist on GitHub](https://gist.github.com/gh-rusinov/cd3f04cd4fa10f8133b203b91f39d726#file-bookswidget-swift-L32). If you can guide me to a right direction... – Igor R. Sep 18 '20 at 13:16
  • It looks like you're mixing up different `managedObjectContext` variables. For start, what is `@Environment(\.managedObjectContext) var moc` in BooksWidget - *how* is it initialised? If you're not sure how to use managedObjectContext you can always use a global Core Data Stack and access it from there - see [this answer](https://stackoverflow.com/a/61572075/8697793). – pawello2222 Sep 18 '20 at 20:04

0 Answers0