Pausing timer when app is in background state Swift

user528432 picture user528432 · Dec 29, 2014 · Viewed 11.2k times · Source

My ViewController.swift

func startTimer() {
    timer = NSTimer().scheduleTimerWithTimerInvterval(1.0,target: self,selctor: Selector("couting"),userinfo: nil, repeats: true)
}

func pauseTimer() {
    timer.invalidate()
    println("pausing timer")
}

and this is appDelegate.swift

func applicateWillResignActive(application: UIApplication) {
    viewController().pauseTimer()
    println("closing app")
}

It is printing pausing timer and closing app but when I open again I see it never paused. How do I do it correctly?

Answer

Suresh Kumar Durairaj picture Suresh Kumar Durairaj · Dec 30, 2014

You have to set an observer listening to when the application did enter background. Add the below line in your ViewController's viewDidLoad() method.

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)

Add the below function to receive the notification.

func myObserverMethod(notification : NSNotification) {
    println("Observer method called")

    //You may call your action method here, when the application did enter background.
    //ie., self.pauseTimer() in your case.
}

Happy Coding !!!