Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you detect when a UIViewController has been dismissed or popped?

I have some cleanup that needs to be performed in a shared resource any time one of my view controllers is dismissed/popped/unloaded? This could either be when the user hits the back button on that individual screen or if a call to popToRootViewController is made (in which case, I would ideally be able to clear up every controller that was popped.)

The obvious choice would be to do this in viewDidUnload, but of course, that isn't how unload works. Is there a way to catch all cases to where the ViewController is removed from the stack?

edit:Forgot to mention that I am doing this using Xamarin so that may or may not impact the answers.

like image 928
cain Avatar asked Oct 27 '14 18:10

cain


People also ask

What is dismiss Swift?

dismiss(animated:completion:) Dismisses the view controller that was presented modally by the view controller.

What is UIViewController life cycle?

The LifecycleThe view controller lifecycle can be divided into two big phases: the view loading and the view lifecycle. The view controller creates its view the first time the view is accessed, loading it with all the data it requires. This process is the view loading.

How do you dismiss a popover?

To dismiss the popover after creation, call the dismiss() method on the Popover instance. The popover can also be dismissed from within the popover's view by calling the dismiss() method on the ViewController.


3 Answers

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    if (isBeingDismissed() || isMovingFromParentViewController()) {
        // clean up code here
    }
}

EDIT for swift 4/5

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    if (isBeingDismissed || isMovingFromParent) {
        // clean up code here
    }
}
like image 128
Cymric Avatar answered Oct 05 '22 06:10

Cymric


-dealloc is probably your best bet. The view controller will be deallocated when it is popped from the stack, unless you are retaining it elsewhere.

viewWillDisappear: and viewDidDisappear: aren't good choices because they are called any time the view controller is no longer shown, including when it pushes something else on the stack (so it becomes second-from-the-top).

viewDidUnload is no longer used. The system frameworks stopped calling this method as of iOS 6.

like image 23
Steve Madsen Avatar answered Oct 05 '22 05:10

Steve Madsen


Building upon @Enricoza's comment, if you do have your UIViewController embedded in a UINavigationController, try this out:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if ((navigationController?.isBeingDismissed) != nil) {
        // Add clean up code here
    }
}
like image 44
PGSeattle Avatar answered Oct 05 '22 05:10

PGSeattle