Post

Replies

Boosts

Views

Activity

Help getting elements from SwiftData in AppIntent for widget
Hello, I am trying to get the elements from my SwiftData databse in the configuration for my widget. The SwiftData model is the following one: @Model class CountdownEvent { @Attribute(.unique) var id: UUID var title: String var date: Date @Attribute(.externalStorage) var image: Data init(id: UUID, title: String, date: Date, image: Data) { self.id = id self.title = title self.date = date self.image = image } } And, so far, I have tried the following thing: AppIntent.swift struct ConfigurationAppIntent: WidgetConfigurationIntent { static var title: LocalizedStringResource { "Configuration" } static var description: IntentDescription { "This is an example widget." } // An example configurable parameter. @Parameter(title: "Countdown") var countdown: CountdownEntity? } Countdowns.swift, this is the file with the widget view struct Provider: AppIntentTimelineProvider { func placeholder(in context: Context) -> SimpleEntry { SimpleEntry(date: Date(), configuration: ConfigurationAppIntent()) } func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry { SimpleEntry(date: Date(), configuration: configuration) } func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> { var entries: [SimpleEntry] = [] // Generate a timeline consisting of five entries an hour apart, starting from the current date. let currentDate = Date() for hourOffset in 0 ..< 5 { let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)! let entry = SimpleEntry(date: entryDate, configuration: configuration) entries.append(entry) } return Timeline(entries: entries, policy: .atEnd) } // func relevances() async -> WidgetRelevances<ConfigurationAppIntent> { // // Generate a list containing the contexts this widget is relevant in. // } } struct SimpleEntry: TimelineEntry { let date: Date let configuration: ConfigurationAppIntent } struct CountdownsEntryView : View { var entry: Provider.Entry var body: some View { VStack { Text("Time:") Text(entry.date, style: .time) Text("Title:") Text(entry.configuration.countdown?.title ?? "Default") } } } struct Countdowns: Widget { let kind: String = "Countdowns" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in CountdownsEntryView(entry: entry) .containerBackground(.fill.tertiary, for: .widget) } } } CountdownEntity.swift, the file for the AppEntity and EntityQuery structs struct CountdownEntity: AppEntity, Identifiable { var id: UUID var title: String var date: Date var image: Data var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(title)") } static var defaultQuery = CountdownQuery() static var typeDisplayRepresentation: TypeDisplayRepresentation = "Countdown" init(id: UUID, title: String, date: Date, image: Data) { self.id = id self.title = title self.date = date self.image = image } init(id: UUID, title: String, date: Date) { self.id = id self.title = title self.date = date self.image = Data() } init(countdown: CountdownEvent) { self.id = countdown.id self.title = countdown.title self.date = countdown.date self.image = countdown.image } } struct CountdownQuery: EntityQuery { typealias Entity = CountdownEntity static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Countdown Event") static var defaultQuery = CountdownQuery() @Environment(\.modelContext) private var modelContext // Warning here: Stored property '_modelContext' of 'Sendable'-conforming struct 'CountdownQuery' has non-sendable type 'Environment<ModelContext>'; this is an error in the Swift 6 language mode func entities(for identifiers: [UUID]) async throws -> [CountdownEntity] { let countdownEvents = getAllEvents(modelContext: modelContext) return countdownEvents.map { event in return CountdownEntity(id: event.id, title: event.title, date: event.date, image: event.image) } } func suggestedEntities() async throws -> [CountdownEntity] { // Return some suggested entities or an empty array return [] } } CountdownsManager.swift, this one just has the function that gets the array of countdowns func getAllEvents(modelContext: ModelContext) -> [CountdownEvent] { let descriptor = FetchDescriptor<CountdownEvent>() do { let allEvents = try modelContext.fetch(descriptor) return allEvents } catch { print("Error fetching events: \(error)") return [] } } I have installed it in my phone and when I try to edit the widget, it doesn't show me any of the elements I have created in the app, just a loading dropdown for half a second: What am I missing here?
0
0
66
Apr ’25
Help with Widget Configuration
Hello, I'm working on my first app. It's also my first encounter with App Intents. I have a data structure for events that has an ID (String), a name (String), a Date and an image (Data). The user can create them in the app and they are stored with CoreData. I wanted to have a widget that would allow the user to choose from their list of events and display that event in the widget. The list should appear in the widget configuration and it would be a list of the names and (if possible) the image. I think I have found how to access the information from the widget, but I cannot figure out how to have the list appear in the configuration. I have been following this guide: https://developer.apple.com/documentation/widgetkit/making-a-configurable-widget?utm_source=pocket_saves. But that one shows hardcoded elements in the list and I haven't been able to find how to have the list change in relation to the content of the app. This is what I have made so far in the AppIntent file: import WidgetKit import AppIntents import CoreData struct EventDetail: AppEntity { static var defaultQuery: EventQuery = EventQuery() var id: String var date: Date var image: Data var title: String static var typeDisplayRepresentation: TypeDisplayRepresentation = "Event" var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(id) \(title)") } } struct EventQuery: EntityQuery{ func entities(for identifiers: [EventDetail.ID]) async throws -> [EventDetail] { return fill_event_details(events_list: getEventDataIntent()) } func suggestedEntities() async throws -> [EventDetail] { fill_event_details(events_list: getEventDataIntent()).filter { $0.id != "-" } } func defaultResult() async -> EventDetail? { try? await suggestedEntities().first } } struct ConfigurationAppIntent: WidgetConfigurationIntent { static var title: LocalizedStringResource = "Select an event" static var description = IntentDescription("This is an example widget.") // An example configurable parameter. @Parameter(title: "Event") var event: EventDetail // init(events: [UserCountdowns]) { // self.event = fill_event_details(events_list: events)[0] // print("AppIntent") // print(self.event.title) // } init() { } } func fill_event_details(events_list: [UserCountdowns]) -> [EventDetail] { var entities_list: [EventDetail]? let events = getEventDataIntent() for event in events { entities_list!.append(EventDetail(id: event.id!, date: event.date!, image: event.image!, title: event.title!)) } return entities_list ?? [EventDetail(id: "-", date: Date(), image: Data(), title: "empty")] } func getEventDataIntent() -> [UserCountdowns] { let context = PersistenceController.shared.container.viewContext let request = UserCountdowns.fetchRequest() var result: [UserCountdowns]! do { result = try context.fetch(request) } catch { print(error) } return result } I have been trying a few things in the widget's code but I haven't been able to make anything work, so I don't really have anything worth sharing, I think. This is the code for the UserCountdowns structure: extension UserCountdowns { @nonobjc public class func fetchRequest() -> NSFetchRequest<UserCountdowns> { return NSFetchRequest<UserCountdowns>(entityName: "UserCountdowns") } @NSManaged public var date: Date? @NSManaged public var image: Data? @NSManaged public var title: String? @NSManaged public var id: String? } Could anyone help me with this, please? What am I missing or what would the next step be? Let me know if there is any other part of the code I should share. Thank you in advance!
0
0
869
Dec ’23