I want to fetch data from SwiftData on Widget but it returns empty data even though there are some data. How can I fetch data correctly? Do I need to setup something in widget target to communicate with the main macOS app?
struct Provider: AppIntentTimelineProvider {
@MainActor func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationAppIntent(), items: getItems())
}
func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry {
await SimpleEntry(date: Date(), configuration: configuration, items: getItems())
}
func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> {
return Timeline(entries: [await SimpleEntry(date: Date(), configuration: configuration, items: getItems())], policy: .after(.now.advanced(by: 60 * 10)))
}
@MainActor func getItems() -> [Item] {
let container: ModelContainer(for: Item.self)
let descripter = FetchDescriptor<Item>()
let items = try? container.mainContext.fetch(descripter)
return items ?? []
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationAppIntent
let items: [Item]
}
I just had to set App Groups for macOS app and widget targets
This is the way to add App groups https://useyourloaf.com/blog/sharing-data-with-a-widget/