Skip to content

viewWillAppear() doesn’t fire when returning from the background

A source of common iOS bugs (believe me, I know!) is that a view controllers .viewWillAppear can’t always be relied upon to update an app’s UI. When an app is returned from the background this method isn’t invoked as in the app’s own little world the view has been the active view all along. Seeing as I just had to look up the notification name yet again, I thought it worth doing quick post, if only for my own reference next time around 😀

If it’s important to update the UI when returning from the background, which tends to be the case when the content presented is determined by date or time, it’s necessary to use NotificationCentre and register an observer for the UIApplication.willEnterForegroundNotification event.

class MyViewController: UIViewController {

override func viewDidLoad() {
  super.viewDidLoad()
  NotificationCenter.default.addObserver(self, 
                   selector: #selector(appEnteredForeground), 
                   name: UIApplication.willEnterForegroundNotification,
                   object: nil)
// all the usual stuff...
}

@objc func appEnteredForeground(){
 //refresh content / view appropriately
}

//don't forget to cancel it when it's job is done
//the safe/easy way is to remove all the object's observers

deinit {
  NotificationCenter.default.removeObserver(self)
}

Leave a Reply