How to detect exit via navigation controller Back button?

I have an app that uses a Navigation Controller. When the user clicks the Back button in the Navbar the segue that initiated the view is unwound but none of the unwind methods are notified. I can't seem to find an official way to detect the exit in the leaving View Controller. I did find that


didMoveToParentViewController(parent: UIViewController?)


when parent was nil did seem to indicate that the view was exiting.

What I need to do is remove the observers that I have set and close a bluetooth connection before I exit

But is there an "official" way to detect the exit?

Accepted Answer

Can't you use any of:

viewWillDisappear

viewDidDisappear

viewDidUnload

Those look interesting. If I segue from this view to another one will any of those trigger? Maybe the "disappear" ones might be good to use...


Thanks for the idea. I'll try them and let you know.

viewDidUnload is deprecated and no longer called, but the others could work.

viewDidUnload isn't available any more but view{will,did}Appear are reliable for observation control. The method I was using was working but maybe by coincidence.


Thanks

This method in UINavigationBarDelegate is made for that.


optional func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem)

I believe this is for removing an item on the Navigation Bar itself not for poping a viewcontroller off the navigation cotroller's stack

How to detect exit via navigation controller Back button?
 
 
Q