12

Is there a way to tell if a new controller came from a navigation back button or was pushed onto the stack? Id like to reload data only for pushing on the navigation stack, not on a back button press.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

3 Answers3

24

As of iOS 5.0 you can do this:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (self.isBeingPresented || self.isMovingToParentViewController) {
        // "self" is being shown for the 1st time, not because of a "back" button.
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 3
    This will not work if your view controller is the first view controller on tab of a tab bar controller. It will work the first time, but thereafter switching to it's tab will appear as if it was a back action because neither `isBeingPresented` nor `isMovingToParentViewController` will be true. Such a case is rare, but if this is your situation check out http://stackoverflow.com/a/40801594/5152481 – gwest7 Nov 25 '16 at 10:48
  • This does not seem to work in iOS10 - both isBeingPresented and isMovingToParentViewController are both false the first time my view controller is presented. – Kendall Helmstetter Gelner Dec 13 '16 at 22:17
  • @KendallHelmstetterGelner Are you calling those in `viewWill|DidAppear` or `viewWill|DidDisappear`? They only work in those 4 methods. – rmaddy Dec 13 '16 at 22:18
  • @maddy - Yes, I'm talking about the standard viewWillAppear: method. Both values on the current VC came up as false in iOS10. – Kendall Helmstetter Gelner Dec 26 '16 at 03:44
1

If your push also includes instantiating the view controller, put your push-only logic in viewDidLoad. It will not be called on back because it has already been loaded.

coneybeare
  • 33,113
  • 21
  • 131
  • 183
1

You could implement the UINavigationControllerDelegate and override the `navigationController:didShowViewController:animated:' method. You'll then have to check the returned view controller to make a determination as to whether you came back from the expected view controller.

- (void)navigationController:(UINavigationController*)navigationController didShowViewController:(UIViewController*)viewController animated:(BOOL)animated
{
    if (yourPushedViewController == viewController)
    {
        // Do something
    }
}
Ron
  • 1,249
  • 9
  • 20