Search code examples
swifttimercountdown

How to create a user defined countdown timer in Swift?


How can I create a user defined countdown timer in Swift?

I got 2 pages in my app. On first page I ask user to write in UITextField a value as hour (for ex: 3), then with segue.identifier, I pass this information to second page, and I want to make a countdown from 3 hours as 02:59:59 format and print it in UILabel. Thanks


Solution

  • I made you a playground with an example of countdown with a NSTimer.

    import UIKit
    
    class MyClass {
    
      var timerCounter:NSTimeInterval!
    
      func stringFromTimeInterval(interval: NSTimeInterval) -> String {
        let interval = Int(interval)
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let hours = (interval / 3600)
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
      }
    
      func startTimer(hour:Int) {
        timerCounter = NSTimeInterval(hour * 60 * 60)
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onTimer:", userInfo: nil, repeats: true)
      }
    
      @objc func onTimer(timer:NSTimer!) {
        // Here is the string containing the timer
        // Update your label here
        println(stringFromTimeInterval(timerCounter))
        timerCounter!--
      }
    }
    
    var anInstance = MyClass()
    
    // Start timer with 3 hours
    anInstance.startTimer(3)
    CFRunLoopRun()