How to detect when app moves to background or foreground

As we know, there is implemented some methods for triggering an application's lifecycle:

iOS Application Lifecycle

There is an issue. These methods didn't help us when the app moves to background or foreground! it just shows us the one-time creation of UIViewControl or process of destroying.

But as the guides in docs there is more information about application lifecycle.

When your app goes to background, The Cocoa broadcasts a notification with the message of the app is moving to the background. So, if your app or your UIViewController registered for this notification, you can be aware when your app moves to background:

iOS Application Moves to Background

As the same, for Moving to Foreground, we have a notification too:

iOS Application Moves to Foreground

So, you have two ways to detect when your app moves to background or foreground:

In AppDelegate

That implemented by default in app delegation, and you can use these default methods for the issue:

func applicationDidEnterBackground(_ application: UIApplication) {
    print("applicationDidEnterBackground")
}

func applicationWillEnterForeground(_ application: UIApplication) {
    print("applicationWillEnterForeground")
}

In UIViewController

If you want to detect it in a UIViewController manually, you should register for the UIApplicationWillEnterForeground or UIApplicationDidEnterBackground notification anywhere in your app. That it's triggered when the user pressed the home button and it moves to the background, and then pressed double and choose app so it moves to the foreground.

  • foreground
override func viewDidLoad() {
    super.viewDidLoad()

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}

func appMovedToForeground() {
    print("App moved to ForeGround!")
}
  • Background
override func viewDidLoad() {
    super.viewDidLoad()

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
}

func appMovedToBackground() {
    print("App moved to Background!")
}

Did this solution work for you? Please pass it on! Tweet

© 2020 Delog • Crafted with ❤️ by W3Layouts