works on swift5.0
var timer = Timer()
var secondsPassed = 0
var totalTime = 300
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
@objc func update() {
if secondsPassed < totalTime{
secondsPassed += 1
}else{
timer.invalidate()
print("Time's up")
}
@IBAction func start(sender: UIButton) {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
startTime = NSDate() // new instance variable that you would need to add.
}
func update() {
let elapsedTime = NSDate().timeIntervalSinceDate(startTime)
let currTime = totalTime - elapsedTime
//total time is an instance variable that is the total amount of time in seconds that you want
countDown.text = String(currTime)
if currTime < 0 {
timer.invalidate()
//do other stuff that you need to do when time runs out.
}
}
var secondsRemaining = 60
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
if secondsRemaining > 0 {
print("(secondsRemaining) seconds.")
secondsRemaining -= 1
}
}
var timer = NSTimer()
timer(timeInterval: 0.01, target: self, selector: update, userInfo: nil, repeats: false)