Skip to main content

How to access a SwiftData container from widgets

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to access a SwiftData container from widgets 관련

SwiftData by Example

Back to Home

How to access a SwiftData container from widgets | SwiftData by Example

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:

  1. Go to your main app target's Signing & Capabilities, and add the App Groups capability.
  2. Click [+] and add a new group, or select one you made previously.
  3. Repeat steps 1 and 2 for your widget.
  4. Make sure whatever Swift files contain your SwiftData models have been added to both your app and widget targets.
  5. Add the modelContainer() modifier to your widget, e.g. in your StaticConfiguration or AppIntentConfiguration.

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()

이찬희 (MarkiiimarK)
Never Stop Learning.