Pausing timer when app is in background state Swift

Accepted answer by @Suresh in Swift 3

Set an observer listening to when the application did enter background in your ViewController's viewDidLoad() method.

 NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)

Add the below function to receive the notification.

 func myObserverMethod(notification : NSNotification) {

   print("Observer method called")

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

}

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 !!!


Updated Answer for Swift 5:

NotificationCenter.default.addObserver
              (self,
               selector: #selector(myObserverMethod),
               name:UIApplication.didEnterBackgroundNotification, object: nil)

@objc func myObserverMethod() {
    print("Write Your Code Here")
}