Search code examples
swiftuiapplicationnotificationcenter

Regarding Notification Center Observers for UIApplicationWillEnterForeground Swift


Hello everyone and thanks for taking the time to read this. I have a table view controller with a header that needs to be refreshed to display the latest content after the user brings the application to the foreground, so I added an observer in viewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(self.setupHeaderView), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)

That works fine, and then I remove the observer in the deinit code as follows:

NotificationCenter.default.removeObserver(self)

My question is if this is the correct implementation of how to do this or have I missed a step? I've read several threads regarding observers as well as the docs, and this seems sufficient to me.

Everything works fine, the only reason I ask is that this is a production environment and I don't want there to be issues going forward related to the code, so I'd like to be sure this is indeed correct.

Thanks in advance.


Solution

  • You're fine, this is a valid approach. If you're targeting iOS 9 and above, you can even get rid of the removeObserver call, because that's handled automatically, as per the Foundation Release Notes