Swift Timeline .after policy not updating at exact time

I am facing an issue with the .after policy in SwiftUI Timeline. The update is not occurring at the exact time I have specified; there are delays ranging from 5 minutes to 3 minutes, etc. How can I resolve this issue? What can I do to ensure that the update happens precisely at the specified time without any delay?

Code Example:

struct SimpleEntry: TimelineEntry {
    let date: Date
}

func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
    // For example, a future date and time: 2024-02-01 12:00:00
    let refreshDateComponents = DateComponents(year: 2024, month: 2, day: 1, hour: 12, minute: 0, second: 0)
    
    // Create a Date object using the specified date and time
    if let refreshDate = Calendar.current.date(from: refreshDateComponents) {
        // Create a SimpleEntry using the generated Date object
        let entry = SimpleEntry(date: refreshDate)
        
        // Create a Timeline and perform the completion with it
        let timeline = Timeline(entries: [entry], policy: .after(refreshDate))
        completion(timeline)
    }
    // Return an empty Timeline in case of an error
    else {
        let emptyTimeline = Timeline(entries: [], policy: .never)
        completion(emptyTimeline)
    }
}
  • There is nothing you can do because that is not how the widget update system works at all. Any request to update the widgets is a suggestion and the system will schedule the update as it wants. The only way to get your widget to change at an exact time is to schedule a timeline entry for that time, but that requires knowing what it will look like in advance.

    Notice that the policy you are using is “after” and not “at”. It is telling the system to wait until at least the specified time.

  • I appreciate your response. I did try the .atEnd method as well. However, achieving an update at the exact planned time seems to be challenging, and there is always some delay. It can even be as long as 10 minutes at times. Could you please share an example code that guarantees an update precisely at the scheduled time?

Add a Comment