Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do viewWillDisappear / viewDidDisappear get called when switching apps?

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?

like image 836
gabor Avatar asked Sep 10 '13 20:09

gabor


2 Answers

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.

like image 37
kgreenek Avatar answered Sep 24 '22 03:09

kgreenek


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()
    }
}
like image 158
Trenskow Avatar answered Sep 24 '22 03:09

Trenskow