- (void)applicationWillResignActive:(UIApplication *)application on your app delegate. You can also register for the UIApplicationWillResignActiveNotification notification on other objects.
You don't necessarily need to pause the timer, though. If you don't do anything, the app will get put to sleep anyway and won't execute any code. Presumably your timer will fire when you become active again (if you do). If you need to do something special there are 'did become active' delegate methods and notifications you can register for as well.
On your applications AppDelegate the (void)applicationDidEnterBackground:(UIApplication *)application method will be called by iOS. You can stop your timer in there.
You can have any class interested in when the app goes into the background receive notifications. This is a good alternative to coupling these classes with the AppDelegate.
dynamic private func applicationWillResignActive() {
// Do things here
}
Apple encourages us to avoid dynamic dispatch and Objective-C selectors whenever possible in Swift, but this is still the most convenient way to do this.
only a side note:
If you register a controller A to be notified going background, be careful that it will be called even if you (for example..) push a second controller B and You are displaying B:
If this behaviour is not correct, is better to register/unregister in
backgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] notification in
// Do what you want to do when app would go to background/ resign active
}
Don't forget to remove observer in deinit
deinit {
if let observer = backgroundObserver {
NotificationCenter.default.removeObserver(observer)
}
}