Probably a simple question, however, I can't seem to conceive an elegant approach.
I want to design a trivial application that allows a timer to be set to a duration (say 1 minute), after that duration the timer should expire, in the duration the timer should update the UI every second.
Thus if the timer is set to one minute, the timer should fire, update the UI every second (by calling a method) and then finally invalidate after 1 minute.
My conundrum is, I can set a
scheduledTimerWithInterval
Swift 3.x code
Make two global variables
var seconds = 1
var secondTimer:Timer?
Then make these two functions
// for setup of timer and variable
func setTimer() {
seconds = 1
secondTimer?.invalidate()
secondTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateUI), userInfo: nil, repeats: true)
}
//method to update your UI
func updateUI() {
//update your UI here
//also update your seconds variable value by 1
seconds += 1
if seconds == 60 {
secondTimer?.invalidate()
secondTimer = nil
}
print(seconds)
}
finally call setTimer()
wherever you want