なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOS How to detect the background transition in UIViewController

Introduction

This article shows hot to detect an entering background and activating from background in UIViewController.

Solution

As you know, UIViewController doesn't have a delegate which is called when it will go background and come back from it.

So, the only way to receive those events is register the UIViewController to a NotificationCenter as below.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(viewWillEnterBackground), name: .UIApplicationWillResignActive, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(viewDidEnterBackground), name: .UIApplicationDidEnterBackground, object: nil)
        
    NotificationCenter.default.addObserver(self, selector: #selector(viewWillEnterForeground), name: .UIApplicationWillEnterForeground , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(viewDidBecomeActive), name: .UIApplicationDidBecomeActive , object: nil)
}

@objc func viewWillEnterBackground() {
    // called when app will enter background
}
    
@objc func viewDidEnterBackground() {
    // called when app entered background
}
    
@objc func viewWillEnterForeground() {
    // called when app will be foreground
}
    
@objc func viewDidBecomeActive() {
    // called when app become active
}