Reputation: 2639
I have created a widget that I would like to update every three seconds.
I have the following code:
struct WidgetModel : TimelineEntry
{
var date: Date
var data: [Data]
}
func getTimeline(in context: Context, completion: @escaping (Timeline<WidgetModel>) -> Void)
{
let controller = DataController()
controller.refresh()
let nextRefresh = Calendar.current.date(byAdding: .second, value: 3, to: Date())!
let model = WidgetModel(date: nextRefresh, data: controller.data)
let timeline = Timeline(entries: [model], policy: .atEnd)
completion(timeline)
}
However, the three seconds will be ignored. The simulator always shows that the next refresh will be in five minutes. I also tried using .after instead of .atEnd, but this did not have any effect. Is five minutes the minimum value or this related to the simulator?
Upvotes: 1
Views: 4738
Reputation: 324
WWDC Meet WidgetKit "Widgets are not an every-second operation...' https://developer.apple.com/videos/play/wwdc2020-10028/?time=1099
WidgetKit is designed to not impact the user's device performance. It does this by minimizing refreshes and URLSession requests. Apple uses metrics about the widgets use and visibility to decide how much processing to allow your app. Seconds based refreshes are not supported.
You need to create a timeline with all the views of the widget in advance. In Apple's WWDC video they recommend you create a timeline for the whole day in advance. After the timeline is created you can use the .atEnd or .after policies to request a new timeline. If something changes in your main app you can ask the timeline to be refreshed.
Upvotes: 5