Detect iOS app entering background

Swift3

let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)


func appMovedToBackground() {
    print("App moved to background!")
}

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
}

In swift 5.x: To observe app enters background event, add this code to your viewDidLoad() method.

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

    @objc func appMovedToBackground() {
        // do whatever event you want
    }

you have to use UIApplication.didEnterBackgroundNotification. If you want to observe if app came to foreground event, use UIApplication.willEnterForegroundNotification

So, the full code will be:

override func viewDidLoad() {
    super.viewDidLoad()

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    
    notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    
    // Do any additional setup after loading the view.
}
 @objc func appMovedToBackground() {
    print("app enters background")
}

@objc func appCameToForeground() {
    print("app enters foreground")
}

Tags:

Ios

Iphone

Swift