Victor Krusenstråhle Victor Krusenstråhle - 2 months ago 32
iOS Question

Stop NSTimer and dismiss view controller (swift)

I am using following code to look for updates in my

firebase
database. I have put the code inside my
viewDidLoad()
.

NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)


When the user has received a file in the database I want the user to goto another
View Controller
. The problem is that either the old
View Controller
is running in the background or the timer does not stop when changing
View Controller
.

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("recievedMission") as! RecievedMissionViewController
self.navigationController!.pushViewController(nextViewController, animated: true)


How do I dismiss the old
View Controller
and how do I stop the
NSTimer
programmably
? Thanks!

Answer

Just store the instance of your timer and then when you are moving to another Controller invalidate the timer, so that first declare one instance of NSTimer.

var timer:NSTimer?

Now use this object to store the reference of your scheduledTimer.

self.timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)

Now on moving to another controller simply.

self.timer.invalidate()
Comments