0

I'm making a widget app that shows today's date and calendar.

I want the widget refresh every midnight, so I tried several methods. But eventually I failed to figure out how to do it.

  • First try : give entries that update every midnight. But it doesn't update the widget every midnight exactly.
struct Provider: TimelineProvider {
  func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {

    var entries: [SomeEntry] = []

    let currentDate = Date()
    let currentEntry = SomeEntry(date: currentDate), content: content)
    entries.append(currentEntry)

    for offset in 1 ..< 5 {
      let day = Calendar.autoupdatingCurrent.date(byAdding: .day, value: offset, to: currentDate)!
      let midnight = Calendar.autoupdatingCurrent.startOfDay(for: day)
      let entry = SomeEntry(date: midnight, content: content)
      entries.append(entry)
    }

    completion(entries, .atEnd)
  }

}

  • Second try : Dynamic Dates

I tried to use dynamic dates which was described here (https://developer.apple.com/documentation/widgetkit/displaying-dynamic-dates)

But it's not customizable, so I think I can't use it when making calendar widget.


  • Third try : Local notification

I tried to use local notification to reload widget every midnight.

But I found in iOS, I can't use silent local notification.


  • Fourth try : Background Tasks

I tried background tasks, but it won't refresh widget if the app is terminated.


I know that other popular widget app's widget updates exact every midnight. Even if I manually change device time, they work.

I think there is a way that can alert widget extension when date changes.

Any idea how to do it??

pawello2222
  • 46,897
  • 22
  • 145
  • 209
HB.K
  • 167
  • 2
  • 12
  • Does this answer your question? [How to change view on midnight in WidgetKit, SwiftUI?](https://stackoverflow.com/questions/64209612/how-to-change-view-on-midnight-in-widgetkit-swiftui) This might help you as well: [Setting the TimelineProvider refresh interval for Widget](https://stackoverflow.com/a/64014799/8697793) – pawello2222 Jan 26 '21 at 11:39
  • I tried those methods, but unfortunately it didn't guarantee the widget refresh every midnight – HB.K Jan 27 '21 at 01:42
  • There is **no guarantee**. You can't actually refresh the widget, you only ask system to refresh it. Please read [Keeping a Widget Up To Date](https://developer.apple.com/documentation/widgetkit/keeping-a-widget-up-to-date). – pawello2222 Jan 27 '21 at 08:49
  • @HB.K did you try with WidgetCenter( manual reloading) and reloadPolicy: .none. – YodagamaHeshan Feb 02 '21 at 09:57

0 Answers0