20
votes

I was wondering if viewWillDisappear: and viewDidDisappear: get called when iOS switches apps (for example, the Home button gets pressed by the user). This would cause the view to disappear from the screen, but do the callbacks get called for this?

2
And what are the results of your testing?Martin R
I'm sure there are folks who have wondered about this. Googling is still faster than coding up a test project.gabor
app delegates only get called during app switching.Gajendra K Chauhan

2 Answers

25
votes

You can.

The solution - which I have used before - is to use the applicationDidEnterBackground: and applicationWillEnterForeground: in your app delegate.

Do this in your app delegate.

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self.window.rootViewController beginAppearanceTransition:NO animated:NO];
    [self.window.rootViewController endAppearanceTransition];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [self.window.rootViewController beginAppearanceTransition:YES animated:NO];
    [self.window.rootViewController endAppearanceTransition];
}

Now your viewWillDisappear:, viewDidDisappear:, viewWillAppear: and viewDidAppear: methods of your view controller hierarchy will get called when you app goes to background and back to foreground.

Hope this works?


Edit 24/11/16 (Swift 3 version)

func applicationDidEnterBackground(_ application: UIApplication) {
    window?.rootViewController?.beginAppearanceTransition(false, animated: false)
    window?.rootViewController?.endAppearanceTransition()
}
   
func applicationWillEnterForeground(_ application: UIApplication) {
    window?.rootViewController?.beginAppearanceTransition(true, animated: false)
    window?.rootViewController?.endAppearanceTransition()
}

Edit 2/1/2017 (all windows)

func applicationDidEnterBackground(_ application: UIApplication) {
    for window in application.windows {
        window.rootViewController?.beginAppearanceTransition(false, animated: false)
        window.rootViewController?.endAppearanceTransition()
    }
}

func applicationWillEnterForeground(_ application: UIApplication) {
    for window in application.windows {
        window.rootViewController?.beginAppearanceTransition(true, animated: false)
        window.rootViewController?.endAppearanceTransition()
    }
}
20
votes

Nope, those methods won't be called in that case.

To be notified when the app goes into the background, you can register for the UIApplicationWillResignActiveNotification notification.

As an aside, the easiest way find out this kind of thing is to just build a super simple app quick and set breakpoints.