I am playing with WidgetKit but I am having a hard time understand how it works. Here is my sample code. I started with create a widget extension and add some more print to understand the life cycle:
@main
struct SampleWidget: Widget {
let kind: String = "SampleWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
SampleWidgetEntryView(entry: entry)
.onAppear {
print("widget appear")
}
.onDisappear {
print("widget disappear")
}
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
.supportedFamilies([.systemMedium])
}
let timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true, block: { timer in
print("timer trigger in widget")
})
}
I would expect when adding the widget, the debug will show as:
- widget appear
- timer trigger in widget (every 5 seconds)
...
When I remove the widget, the debug would show:
- widget disappear
- timer trigger in widget should stop firing
So the first time adding the widget on the home screen, i got the debug trigger correctly. When adding the widget on the Notification Center, i would expect it to get trigger again because it's another instance of the widget, but it does not. When I removed the widget on both side, the onDisappear never get trigger and my timer trigger in widget still get print out. How does this continue to work? Should it just stop firing?
In the old Today Extension Widget, when you swipe to view widget it will trigger viewDidLoad. When you close the widget, it will trigger viewWillDisappear. Is it possible for WidgetKit behave the same way?
I understand WidgetKit extension does not run forever but SwiftUI allow us to update UI dynamically. So at what point after widget is added will it stop working? If I add a background task, when should I expect it to stop working?