Pause timer when app is in Swift background

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") } 

This is a print of the timer to pause and close the application, but when I open it again, I see that it never stopped. How do I do it right?

+7
source share
5 answers

You must establish that the observer is listening when the application really enters the background. Add the line below to the ViewController viewDidLoad () method.

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

Add the function below to receive 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 !!!

+24
source

Accepted answer by @Suresh in Swift 3

Set an observer that listens when the application actually enters the background in the ViewController viewDidLoad () method.

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

Add the function below to receive 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. } 
+2
source

You create a new object and call pauseTimer() on it:

 viewController().pauseTimer() // This line causes issue viewController(), creates a new instance 

Instead of creating a new object, either you must pass this instance to AppDelegate, or call pauseTimer () for an existing object or Listen for UIApplicationDidEnterBackgroundNotification notifications in your view controller class and pause timer from there.

0
source

Updated answer for Swift 4:

 override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil) } @objc func myObserverMethod() { // Call your action method here, when the application did enter background. } 
0
source

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") } 
0
source

Source: https://habr.com/ru/post/1210036/


All Articles