I am using NSTimer
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 ViewController
. The problem is that either the old ViewController
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
or how do I stop the NSTimer
programmatically
? Thanks!
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()
var timer:NSTimer?
timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector:
#selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)
//ToStop Timer
timer.invalidate()
timer = nil
It's a good thing to nil the instance variable timer after having invalidated it, it avoids further confusion if you need to create another timer with the same variable.
// Hi, after timer event completion you need to invalidate that timer as like as follow
yourTimer.invalidate()
To cancel a NSTimer, just use:
timer?.invalidate()
And please make sure your function DriversInterfaceViewController.CheckFormularChild
runs in UIThread (If this method touches UI) or else it'll crash
When the NSTimer haven't invalidate, the instance of view controller stayed in memory and haven't release in ARC. So you need to invalidate the NSTimer when the old view controller disappear.
override func viewWillDisappear(animated: Bool)
{
if self.timer != nil
{
self.timer!.invalidate()
self.timer = nil
}
}
来源:https://stackoverflow.com/questions/39528337/stop-nstimer-and-dismiss-view-controller-swift