How to access a SwiftData container from widgets
How to access a SwiftData container from widgets 관련
Updated for Xcode 15
SwiftData works great with widgets, and it only takes a few minutes to synchronize data between your main app and widgets.
Assuming you already have a widget target added to your project, it takes five steps to configure your widget to share data with your main app:
- Go to your main app target's Signing & Capabilities, and add the App Groups capability.
- Click
[+]
and add a new group, or select one you made previously. - Repeat steps 1 and 2 for your widget.
- Make sure whatever Swift files contain your SwiftData models have been added to both your app and widget targets.
- Add the
modelContainer()
modifier to your widget, e.g. in yourStaticConfiguration
orAppIntentConfiguration
.
And that's it: when your app runs next, SwiftData will automatically copy any existing data into the shared app group so it's accessible by your widget.
At this point you can go ahead and use SwiftData normally inside your widget, for example using @Query
inside your widget view, modifying data, and so on.
One thing to be mindful of is that iOS limits how often widgets are refreshed, so you should explicitly ask for a widget refresh when you know something important has changed.
To do that, first add an import for WidgetKit, then call this:
WidgetCenter.shared.reloadAllTimelines()