Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make count down timer with completion handler in swift

Tags:

ios

swift

timer

Currently I am trying to Create a 3...2...1... Go! type of count down where right after Go! is stated an action occurs however the option to use the completion handler for Timer.scheduleTimer doesn't have the ability to countdown from what I understand?

As of now I can count down from 3 but don't know how to invalidate the timer at Go! and perform an action

var seconds = 3
var countDownTimer = Timer()

func startCountDown() {
  countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TrackActivityVC.updateTimer), userInfo: nil, repeats: true)
}

func updateTimer() {

  seconds -= 1
  print(seconds)
}

// Not sure how to use this code to create a countdown, as it doesn't seem possible with this method

Timer.scheduledTimer(withTimeInterval: someInterval, repeats: false) {

}

Thus the question is How to make count down timer with completion handler.

like image 975
lifewithelliott Avatar asked Jul 01 '17 03:07

lifewithelliott


1 Answers

Here is how to create a countdown timer using the trailing closure syntax:

var seconds = 3

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
    self.seconds -= 1
    if self.seconds == 0 {
        print("Go!")
        timer.invalidate()
    } else {
        print(self.seconds)
    }
}

Here is a better version that invalidates the timer when the viewController is deinitialized. It uses [weak self] to avoid hanging on to the viewController if it closes:

class MyViewController: UIViewController {
    var seconds = 3
    var myTimer: Timer?

    func startCountdown() {
        myTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            self?.seconds -= 1
            if self?.seconds == 0 {
                print("Go!")
                timer.invalidate()
            } else if let seconds = self?.seconds {
                print(seconds)
            }
        }
    }

    deinit {
        // ViewController going away.  Kill the timer.
        myTimer?.invalidate()
    }
}
like image 177
vacawama Avatar answered Sep 22 '22 15:09

vacawama