Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Proof of concept of using caches in WidgetKit
Most of this file has been omitted to only focus on the caching aspect, but in reality
it would be a standard widget template.
struct MyWidgetProvider: IntentTimelineProvider {
// Initialise the cache.
private let cache = MyWidgetCache()
func getEntries(for configuration: ConfigurationIntent, in context: Context, completion: @escaping ([MyWidgetEntry]?) -> ()) {
getWorkouts { error, workouts in
// If something goes wrong, try to use a cached entry.
if let error = error {
guard let cachedEntry = cache.newEntryFromPrevious(withDate: Date()) else {
// If no errors, make an entry, cache it, and return it.
let entry = MyWidgetEntry(date: Date(), configuration: configuration, workoutsCount: workouts.count)
cache.previousEntry = entry
class MyWidgetCache: WidgetCache {
typealias TimelineEntryType = MyWidgetEntry
var previousEntry: TimelineEntryType? = nil
func newEntryFromPrevious(withDate date: Date) -> TimelineEntryType? {
guard let previousEntry else { return nil }
return MyWidgetEntry(
date: date,
configuration: previousEntry.configuration,
workoutsCount: previousEntry.workoutsCount
protocol WidgetCache {
associatedtype TimelineEntryType: TimelineEntry
var previousEntry: TimelineEntryType? { get set }
func newEntryFromPrevious(withDate date: Date) -> TimelineEntryType?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment