Access SwiftData in Widgets

How do I access the SwiftData ModelContainer of my app inside the widget extension?

Following the guide to add a Widget Extension I’ve added the necessary target to my project and enabled App Groups.

I’ve seen that the Backyard Birds example code offers an example how to build this, but it encapsulates the SwiftData handling in a separate app package. Therefore the example simply points to the app package. Though, in my case I don’t host my SwiftData in an external app package, but simply inside the regular app target.

So, my question is how and at which point in code do I need to access the ModelContainer?

Answered by DTS Engineer in 790476022

Your widget can't access the model container created in your app because it runs in its own process. To access SwiftData, your widget needs to create its own model container, typically, in its timeline provider. The following Apple sample shows that: Adopting SwiftData for a Core Data app.

After downloading the sample, you can open the SwiftData project (Source/Trips-SwiftData/SampleTrips.xcodeproj), and find the relevant code in TripsWidget.swift.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Your widget can't access the model container created in your app because it runs in its own process. To access SwiftData, your widget needs to create its own model container, typically, in its timeline provider. The following Apple sample shows that: Adopting SwiftData for a Core Data app.

After downloading the sample, you can open the SwiftData project (Source/Trips-SwiftData/SampleTrips.xcodeproj), and find the relevant code in TripsWidget.swift.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Access SwiftData in Widgets
 
 
Q