Make sure you already understand and watch some tutorials on how to set up your widget to follow along with this article. I will only focus on explaining the widget timeline in this short article.
To set up the widget timeline, you need to initialise it with an array ofTimelineEntry objects and TimelineReloadPolicy, Timeline(entries: [EntryType], policy: TimelineReloadPolicy).
Each TimeEntry object has a date and time. And, there are 3 types of TimelineReloadPolicy according to Apple documentation:
- atEnd – A policy that specifies that WidgetKit requests a new timeline after the last date in a timeline passes.
- after(_ date: Date) – A policy that specifies a future date for WidgetKit to request a new timeline.
- never – A policy that specifies that the app prompts WidgetKit when a new timeline is available.
By default, Apple sets the refresh policy to atEnd. It is useful when you already have the value that you want to update in your widget and know when you want to update them. For example, if you are developing a strategy gaming app that let users build their empires by building different infrastructures like Barracks, Schools, Town Hall, etc and also set a time required for those infrastructures to finish building, you can use a widget to show the progress of each building before it finishes. Here is a sample. (I didn’t create the project, so the code might not work but you get the idea)
Secondly, if the users in your app decided to upgrade or build more infrastructures, therefore increase the overall building time, then you might want to use .after(date) to update the widget before the current timeline has finished.
Then, when the building progress has reached 100%, you can set the refresh policy to .never, so that the widget won’t ask for a new timeline unless we trigger it from the app using WidgetCenter.shared.reloadAllTimelines() or WidgetCenter.shared.reloadTimelines(ofKind: your_widget_bundle_id).