Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Countdown timer in Swift

How do i set a timer to countdown from (x)secs and then end the game when the timer reaches 0secs. I need the timer to start when a button is pressed and continue when the next ViewCotroller is being shown. When the timer is done I need to show another View. (I'm new to developing Apps and swift etc.)

2 Answers

have a look at NSTimer.

A timer waits until a certain time interval has elapsed and then fires, sending a specified message to a target object

so you could create a timer that waits for x seconds and then performs a segue to your new view controller

in viewWillAppear of your viewController you could create the timer like so:

let timer = scheduledTimerWithTimeInterval(10, target: self, selector: "timerFinished:", userInfo: nil, repeats: false)

then in that same view controller you would need to implement the method that gets fired when the time is up (the selector you passed in to the timerWithTimeInterval method:

func timerFinished(timer: NSTimer) {

   //perform segue here

}

When i tried to run this on my device i get an error -

"Use of unresolved identifier 'scheduledTimerWithTimeInterval'

How do i say Show ViewControllerXYZ in.. func timerFinished(timer: NSTimer) {

//perform segue here

}

if you are using storyboards you would create a segue between the two view controllers in your storyboard then call the performSegueWithIdentifer method

func timerFinished(timer: NSTimer) {

//perform segue here
self.performSegueWithIdentifier("someIdentifier", sender: self)
}

Also how do I stop the timer when a button is pressed?

to stop the timer you invalidate it:

timer.invalidate()

so you would just place the above code in the IBAction function for the button

I get the error "use of unresolved identifier" when type that in the IBAction method for the button