How to set several subsequent countdown timers in Swift












-2














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)
}

}









share|improve this question









New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Your problem is at line 17
    – Leo Dabus
    15 hours ago










  • I forgot to leave my code here...
    – Mikhail Tseitlin
    15 hours ago










  • Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
    – Leo Dabus
    15 hours ago












  • Thank you! Already did it!
    – Mikhail Tseitlin
    15 hours ago






  • 1




    You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
    – Leo Dabus
    14 hours ago


















-2














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)
}

}









share|improve this question









New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Your problem is at line 17
    – Leo Dabus
    15 hours ago










  • I forgot to leave my code here...
    – Mikhail Tseitlin
    15 hours ago










  • Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
    – Leo Dabus
    15 hours ago












  • Thank you! Already did it!
    – Mikhail Tseitlin
    15 hours ago






  • 1




    You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
    – Leo Dabus
    14 hours ago
















-2












-2








-2


1





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)
}

}









share|improve this question









New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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)
}

}






swift timer






share|improve this question









New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 12 hours ago









user1118321

19.6k44266




19.6k44266






New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 19 hours ago









Mikhail Tseitlin

42




42




New contributor




Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Mikhail Tseitlin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Your problem is at line 17
    – Leo Dabus
    15 hours ago










  • I forgot to leave my code here...
    – Mikhail Tseitlin
    15 hours ago










  • Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
    – Leo Dabus
    15 hours ago












  • Thank you! Already did it!
    – Mikhail Tseitlin
    15 hours ago






  • 1




    You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
    – Leo Dabus
    14 hours ago




















  • Your problem is at line 17
    – Leo Dabus
    15 hours ago










  • I forgot to leave my code here...
    – Mikhail Tseitlin
    15 hours ago










  • Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
    – Leo Dabus
    15 hours ago












  • Thank you! Already did it!
    – Mikhail Tseitlin
    15 hours ago






  • 1




    You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
    – Leo Dabus
    14 hours ago


















Your problem is at line 17
– Leo Dabus
15 hours ago




Your problem is at line 17
– Leo Dabus
15 hours ago












I forgot to leave my code here...
– Mikhail Tseitlin
15 hours ago




I forgot to leave my code here...
– Mikhail Tseitlin
15 hours ago












Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
– Leo Dabus
15 hours ago






Please edit your question, post your code with the issues you are facing and what you have tried to solve it.
– Leo Dabus
15 hours ago














Thank you! Already did it!
– Mikhail Tseitlin
15 hours ago




Thank you! Already did it!
– Mikhail Tseitlin
15 hours ago




1




1




You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
– Leo Dabus
14 hours ago






You should never use a timer to calculate elapsed time. Just store a date object (startDate) and display the time interval since now startDate.timeIntervalSinceNow. Note that the result for past date would be negative. If you would like to get a positive result for past dates just use Date().timeIntervalSince(startDate)
– Leo Dabus
14 hours ago














1 Answer
1






active

oldest

votes


















0














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.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Mikhail Tseitlin is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53943029%2fhow-to-set-several-subsequent-countdown-timers-in-swift%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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.






    share|improve this answer


























      0














      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.






      share|improve this answer
























        0












        0








        0






        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.






        share|improve this answer












        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 12 hours ago









        user1118321

        19.6k44266




        19.6k44266






















            Mikhail Tseitlin is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            Mikhail Tseitlin is a new contributor. Be nice, and check out our Code of Conduct.













            Mikhail Tseitlin is a new contributor. Be nice, and check out our Code of Conduct.












            Mikhail Tseitlin is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53943029%2fhow-to-set-several-subsequent-countdown-timers-in-swift%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas