'Function called on viewController close (when application exit)?

I am looking for a function which is called on a UIViewController when the application exits.

I tried it out with viewWillDisappear and with applicationWillTerminate but nothing works.

I want to save my settings from the UIViewController in this function.



Solution 1:[1]

Like @Jeff said, but

In Swift 3:

override func viewDidLoad () {
  super.viewDidLoad()

  NotificationCenter.default.addObserver(self, selector: #selector(suspending), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
  NotificationCenter.default.addObserver(self, selector: #selector(suspending), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
}

func suspending () {
  print("suspending...")
}

UIApplicationWillResignActive happens when the app is swapped out, while UIApplicationWillTerminate is triggered when exiting, such as when the Home button is pressed.

Solution 2:[2]

you can call deinit inside the ViewController

deinit {
   deleteUnsavedPhotoFromServer()
}

Solution 3:[3]

Swift 5.5

Use For App Enter Background

NotificationCenter.default.addObserver(self, selector: #selector(appResignActiveNotify), name: UIApplication.willResignActiveNotification, object: nil)
        
 @objc func appResignActiveNotify() {
       //called when App enter background
   }

For App Terminate

NotificationCenter.default.addObserver(self, selector: #selector(appTerminateNotify), name: UIApplication.willTerminateNotification, object: nil)
        
  @objc func appTerminateNotify() {
       //called when Terminate
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brent Faust
Solution 2 Dan Alboteanu
Solution 3 Mitul Pokiya