Countdown timer in WidgetKit, SwiftUI

Viewed 58

I need to create a widget with a countdown timer, I saw differente resources, but none of them seems to work (even the official apple sample).

Lets say I have an amount of seconds in my main target app, and I access it.

class TimerManager: ObservableObject {


   public static let shared: TimerManager = TimerManager()

   @Published var trainingLenght: Int = 60

   func startTraining() {
     trainingTimerMode = .running
     trainingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in
        self.trainingLenght += 1
     })
   }

My var trainingLenght is now counting down.

How do I display it in my getTimeline method inside my widget? Once I transformed it as a Date, is it correct to use:

Text(entry.date, style: .timer)

?

So far even with the official sample https://developer.apple.com/documentation/widgetkit/adding_widgets_to_the_lock_screen_and_watch_faces I'm not able to see the timer counting down.


Update:

this is how my getTimeline method looks like:

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
    let date = Date()
    let entries = [SimpleEntry(date: date)]
    let timeline = Timeline(entries: entries, policy: .atEnd)
    completion(timeline)
}
0 Answers
Related