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
Junaid Abdurahman
Courses Plus Student 87 PointsCountdown 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
Stone Preston
42,016 Pointshave 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
}
Junaid Abdurahman
Courses Plus Student 87 PointsHow do i say Show ViewControllerXYZ in.. func timerFinished(timer: NSTimer) {
//perform segue here
}
Stone Preston
42,016 Pointsif 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)
}
Junaid Abdurahman
Courses Plus Student 87 PointsAlso how do I stop the timer when a button is pressed?
Stone Preston
42,016 Pointsto stop the timer you invalidate it:
timer.invalidate()
so you would just place the above code in the IBAction function for the button
Junaid Abdurahman
Courses Plus Student 87 PointsI get the error "use of unresolved identifier" when type that in the IBAction method for the button
Junaid Abdurahman
Courses Plus Student 87 PointsJunaid Abdurahman
Courses Plus Student 87 PointsWhen i tried to run this on my device i get an error -
"Use of unresolved identifier 'scheduledTimerWithTimeInterval'