SwiftData in Widgets

up:: SwiftData

Resources

Steps

  1. New > Target > WidgetExtension
  2. Set up App Group
  3. Add Widget to app group

.supportedFamilies

Manually reload widget

WidgetCenter.shared.reloadTimelines(ofKind: "widgetextension")

Share data

How can I share SwiftData @Model between widget and app?

try this:

static private var sharedModelContainer: ModelContainer = {
    let schema = Schema([
        MyModel.self,
    ])
    let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
 
    do {
        return try ModelContainer(for: schema, configurations: [modelConfiguration])
    } catch {
        fatalError("Could not create ModelContainer: \(error)")
    }
}()
 
static var sharedModelContext = ModelContext(Self.sharedModelContainer)