-4

I am making a quiz app using Swift. I want to add a timer that countsdown from 60 seconds (1 minute) so that when it reaches 0, the game is over. How would I add a timer?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Python_Is_Great
  • 889
  • 1
  • 6
  • 8
  • 1
    Take a look at the NSTimer class: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/ – Luke May 29 '15 at 15:47
  • 3
    Welcome to SO! You'll get more help (and fewer downvotes) if you include a little more information in your question :) Have you tried Googling it? Have you tried to write any code that you could put in the post? I just Googled "swift timer" and the #1 hit was this: http://stackoverflow.com/questions/24007518/how-can-i-use-nstimer-in-swift Generally, questions like "How do I do X?" get a lot of criticism, in part because they suggest that SO is being used as a substitute for Google... – Aaron Rasmussen May 29 '15 at 16:00

1 Answers1

0

This could help you, put your appropriate game logic on updateTimer function and stopCountDownTimer function.

class TimerTestViewController: UIViewController  {

var totalSecondsCountDown = 60 // 60 seconds
// timer
var timer : NSTimer!

override func viewDidLoad() {
    super.viewDidLoad()

    self.startCountDownTimer()
}

func updateTimer() {

    if self.totalSecondsCountDown > 0 {
        self.totalSecondsCountDown = self.totalSecondsCountDown - 1
        println("timer countdown : \(self.totalSecondsCountDown)")
    }
    else {
        self.stopCountDownTimer();
        println("timer stops ...")
    }

}

func startCountDownTimer() {

    if self.timer != nil {
        self.timer.invalidate()
        self.timer = nil
    }

    if self.totalSecondsCountDown > 0 {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTimer:", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
        self.timer.fire()
    }

}

func stopCountDownTimer() {
    if self.timer != nil {
        self.timer.invalidate()
        self.timer = nil
    }

}
}
regeint
  • 888
  • 2
  • 17
  • 38