I'm working on a game for iOS coded in Swift. I've tried to find a way to detect when the app enters background mode or is interrupted for other reasons, for example a phone call but can't find anything. How do I do it?
To detect if an iOS application is in background or foreground we can simply use the UIApplication just like we can use it to detect many other things like battery state, status etc. The shared. application state is an enum of type State, which consists of the following as per apple documentation.
No. Applications cannot run in the background for over 10 minutes, except for a few certain situations (VOIP, playing audio, etc.) An iOS app which plays audio will keep playing audio indefinitely in the background so long as the audio is playing.
This is done using three steps: Adding a new property to watch an environment value called scenePhase . Using onChange() to watch for the scene phase changing. Responding to the new scene phase somehow.
You can add an observer to your view controller:
edit/update: Xcode 11 • Swift 5
iOS13 or later
UIScene.willDeactivateNotification
iOS12 or earlier
UIApplication.willResignActiveNotification
if #available(iOS 13.0, *) { NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIScene.willDeactivateNotification, object: nil) } else { NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil) }
and add a selector method to your view controller that will be executed when your app receives that notification:
@objc func willResignActive(_ notification: Notification) { // code to execute }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With