onResume/onPause on iOS application

You are looking for

override func viewWillDisappear(animated: Bool) {}

for onPause

and

override func viewWillAppear(animated: Bool) {}

for onResume

Other answers are referring to the application lifecycle callbacks as opposed to controller (Activity in Android) callbacks.


In Swift you can use

    NotificationCenter.default.addObserver(self, selector: #selector(onPause), name:
        UIApplication.willResignActiveNotification, object: nil)
    
    NotificationCenter.default.addObserver(self, selector: #selector(onResume), name:
        UIApplication.willEnterForegroundNotification, object: nil)

with

@objc func onPause() {
    
}

@objc func onResume() {

}

Note that in practice I found replacing UIApplication.willEnterForegroundNotification with UIApplication.didBecomeActiveNotification worked better because onResume is then also triggered if you click the Home button twice to open the iOS 'open apps' screen, then click the app immediately to focus it.


There is a dedicated class that receives delegate callbacks (from the application instance itself) for these events usually called XXXApplicationDelegate.

There you need to implement delegate methods for the application lifecycle.

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

Tags:

Ios