I have a basic Widget with a button to toggle the home lights, the buttons triggers the following AppIntention:
import WidgetKit
import AppIntents
struct ConfigurationAppIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource = "Bulb state"
static var description = IntentDescription("This is an example widget.")
}
struct ToggleStateIntent: AppIntent {
static var title: LocalizedStringResource = "Toggle light state"
init(){
}
func perform() async throws -> some IntentResult {
await WizClient.shared.toggleState()
return .result()
}
}
The problem is that I must be running the app with xcode (in my phone, not simulator) to work fine, when I stop xcode the button must be pressed two times to trigger the AppIntention.
The toggle function works well on the app with a toggle component.
Here is the widget:
import WidgetKit
import SwiftUI
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> {
let timeline = Timeline(entries: [SimpleEntry(date: Date(), configuration: configuration)], policy: .atEnd)
return timeline
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationAppIntent
}
struct BulbActionsEntryView : View {
var entry: Provider.Entry
var body: some View {
HStack {
Button(intent: ToggleStateIntent()){
Text("Toggle")
}
}
.padding(.vertical)
}
}
struct BulbActions: Widget {
let kind: String = "BulbActions"
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in
BulbActionsEntryView(entry: entry)
.containerBackground(.fill.tertiary, for: .widget)
}
}
}
extension ConfigurationAppIntent {
fileprivate static var test: ConfigurationAppIntent {
let intent = ConfigurationAppIntent()
print("Intent -> \(intent)")
return intent
}
}
#Preview(as: .systemSmall) {
BulbActions()
} timeline: {
SimpleEntry(date: .now, configuration: .test)
}