skip to Main Content

How to make a countdown timer daily at a specific time. When I open the application again, the timer is reset and the countdown starts again, I’m trying to figure out how to make the timer start again after its time has elapsed..

For example, so that this timer starts over every day at 6 pm

struct TimerView: View {
    //MARK: - PROPERTIES
    @State var timeRemaining = 24*60*60
    
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    //MARK: - BODY
    var body: some View {
        
        Text("(timeString(time: timeRemaining))")
            .font(.system(size: 60))
            .frame(height: 80.0)
            .frame(minWidth: 0, maxWidth: .infinity)
            .foregroundColor(.white)
            .background(Color.black)
            .onReceive(timer){ _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }else{
                    self.timer.upstream.connect().cancel()
                }
            }
    }
    
    //Convert the time into 24hr (24:00:00) format
    func timeString(time: Int) -> String {
        let hours   = Int(time) / 3600
        let minutes = Int(time) / 60 % 60
        let seconds = Int(time) % 60
        return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
    }
}

2

Answers


  1. the timer is reset and the countdown starts again

    You could try to play with UserDefaults to store variables in the device’s memory.

    Here is the Documentation : https://developer.apple.com/documentation/foundation/userdefaults

    Login or Signup to reply.
  2. Take a look at TimelineView and AppStorage e.g.

    @AppStorage("StartDate") var startDate: Date
    ...
    TimelineView(.periodic(from: startDate, by: 1)) { context in
        AnalogTimerView(date: context.date)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search