Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect iOS app entering background

Tags:

ios

swift

iphone

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?

like image 850
Johannes Flood Avatar asked Jan 12 '16 13:01

Johannes Flood


People also ask

How do I know if an app is running in the background on iOS?

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.

Can iOS apps run in the background?

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.

How do you be notified when your Swiftui app moves to the background?

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.


1 Answers

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 } 
like image 86
Leo Dabus Avatar answered Sep 21 '22 14:09

Leo Dabus