Search code examples
swifttimer

How to set several subsequent countdown timers in Swift


To begin with, in general, I want to build the functionality of the program on a timer, which will alert you about the specified breaks, etc. The program is for concentration.

When saving all the variables that we set at the very beginning, when you press the button, the timer should start. It must perform a specific cycle (period) that we set earlier.

But I have something wrong with the implementation of exactly the same cycle. It seems that all variables are saved, but why the label does not change them ... Ideally, you should first run Work -> Short break -> Work -> Short Break -> Work -> Short Break -> Work -> Short Break -> Long Break and then repeat depending on how many Cycles are installed. But for some reason, I have Work -> Short break -> Short break ...

From you I just want to hear the opinion of what my mistake may be and how to solve it?

For my "code" do not pay attention and do not scold, I know myself. Now I just want to learn how to write and understand what I am writing. The code will of course be better over time.

My app looks like this:

The user interface for the timer app. It shows several text fields for various time intervals and a timer displaying the current interval.

import UIKit

class ViewController: UIViewController {

    var time: Int = 0
    var timer = Timer()

    var min: Int = 0
    var sec: Int = 0

    @IBOutlet weak var shortBreakLabel: UITextField!
    @IBOutlet weak var longBreakLabel: UITextField!
    @IBOutlet weak var workLabel: UITextField!
    @IBOutlet weak var cyclesLabel: UITextField!

    @IBOutlet weak var goButton: UIButton!

    @IBOutlet weak var minutesLabel: UILabel!
    @IBOutlet weak var secondsLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        shortBreakLabel.text = String(5)
        longBreakLabel.text = String(15)
        workLabel.text = String(25)
        cyclesLabel.text = String(16)

        saveTimer()

        goButton.layer.cornerRadius = 10
    }

    //GoButton pressed
    @IBAction func goButtonAction(_ sender: UIButton) {
        timerFunc()
    }

    func timerFunc() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerDidEndend), userInfo: nil, repeats: true)
    }

    @objc private func timerDidEndend() {
        if (time > 0) {
        time -= 1
        updateUI()
        } else {
            timer.invalidate()
        }

       changeTimeToShortBreak()
        changeTimeToWork()
        changeTimeToShortBreak()

    }

    private func updateUI() {
        min = (time/60) % 60
        sec = time % 60

        minutesLabel.text = String(min)
        secondsLabel.text = String(sec)
    }

    func changeTimeToShortBreak() {
        if time == 0 {
            timer.invalidate()
            minutesLabel.text = shortBreakLabel.text
            time = Int(minutesLabel.text!)! * 60
            timerFunc()
        }
    }

    func changeTimeToWork() {
        if time == 0 {
            timer.invalidate()
            minutesLabel.text = workLabel.text
            time = Int(minutesLabel.text!)! * 60
            timerFunc()
        }
    }

    func saveTimer() {
        minutesLabel.text = workLabel.text
        time = Int(minutesLabel.text!)! * 60
    }

    //Hide keyboard function
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        saveTimer()
        self.view.endEditing(true)
    }

}

Solution

  • You really have 2 or 3 different things going on here:

    1. Allowing the user to set time intervals
    2. Displaying the time since the last/to the next interval
    3. Keeping track of the time to figure out what state you're currently in or will be in next

    I would break this into 2 classes - a state class and a UI class. The state class would just have an array of time intervals and an indicator of which one you're on. Something like this:

    var timeIntervals = [ kDefaultWorkInterval, kDefaultShortBreakInterval, kDefaultWorkInterval, kDefaultShortBreakInterval, kDefaultWorkInterval, kDefaultShortBreakInterval, kDefaultWorkInterval, kDefaultShortBreakInterval, kDefaultLongBreakInterval ]
    var currentInterval = 0
    var timer = Timer()
    

    Rather than setting the timer to fire every second, you simply set it to the time in the timeIntervals [ currentInterval ] element. When it fires, increment currentInterval, get the time interval for that interval, and set the timer to fire in that many seconds.

    Next, in your UI class, don't poll for changes to the text fields. Set the UI class (your ViewController) to receive notifications from the text fields when they have been edited. That way you only need to update the state object's time intervals when the user has actually changed them. This is much more efficient than changing them once per second. When that happens call a setter on the state class to update the time intervals.

    I would keep the 1 second timer in the ViewController and simply use it for updating the countdown and nothing else.