How to share CoreData To the widget ?

I am new to swiftui so i was wondering how to share data that we store in coreData to widget in ios 14
Answered by Engineer in 630238022
You'll want to use a group container. The widget and main app can share the same database files with Core Data.

Depending on how complex your model is, and on how static your widget UI is, you might want to go through the extra steps edorphy discusses to mirror out a simplified and stripped down model for the widget. This can get complicated and rigid, so I'm not sure I'd recommend it as approach #1. You can also have a denormalized simplified entity in the database itself. That'll be easier to maintain.

If you get to the point where you're instrumenting each I/O, and counting the 4KB, then a more static view archive can be helpful to accelerate launch time.

I haven't gotten this far in my prototyping yet, but I was going to take the approach of using an app group between my main app target, and the widget extension. I believe this is the correct way to share file space / sandbox container between extensions and main app target.

If this assumption is correct and works for you, then do the following:
  1. Put your heavy CoreData stuff in your main app--it doesn't belong in your widget.

  2. Determine what you want your widget to display

  3. Serialize it to simple files (use the codable protocol or images!)

  4. Use WidgetCenter API and request your timeline provider get an update

  5. In your timeline provider, decode those files and create your timeline entries

  6. Let the widget configuration do the rest

Delete the file from the timeline provider only if it can independently determine that the data is no longer relevant, I'd defer anything heavy weight to your main app so your timeline provider can return your timeline entries as fast as possible. You never know when the user may interact with your widget and your timeline gets reloaded so keep until no longer relevant.

The method for getSnapshot and getTimeline give you a closure to do things async--but you should still return fast as there are probably some underlying timeouts / quality of service expecations in the OS for providing those entries quickly.
Accepted Answer
You'll want to use a group container. The widget and main app can share the same database files with Core Data.

Depending on how complex your model is, and on how static your widget UI is, you might want to go through the extra steps edorphy discusses to mirror out a simplified and stripped down model for the widget. This can get complicated and rigid, so I'm not sure I'd recommend it as approach #1. You can also have a denormalized simplified entity in the database itself. That'll be easier to maintain.

If you get to the point where you're instrumenting each I/O, and counting the 4KB, then a more static view archive can be helpful to accelerate launch time.

How to share CoreData To the widget ?
 
 
Q