Woodstock Woodstock - 6 months ago 55
iOS Question

NSTimer/Timer duration and UI update

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

, it calls a method on the timer interval. If I make this 1 minute I can call a method after one minute to invalidate the timer, but there doesn't seem to be a mechanism to perform calls during this minute.

Can you give me some guidance?




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 = 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 = nil

finally call setTimer() wherever you want