How to check if an iOS program is in foreground or in background?


Knowing when the application is in foreground or in background is important as being an iOS developer we need to handle multiple events such as background downloads, events if the app comes to foreground.

Here we will see how to check if the application is in background or foreground.

We will be using Notification Center for that,

To read more about it you can refer apple document.

 https://developer.apple.com/documentation/foundation/notificationcenter

A notification dispatch mechanism that enables the broadcast of information to registered observers. We will be adding observer to the same and will be getting the call.

Step 1 −  Open Xcode → New Project → Single View Application → Let’s name it “ForegroundBackground”

Step 2 − In viewDidLoad create an object of Notification Center

let notificationCenter = NotificationCenter.default

Step 3 − Add observer for background and foreground

notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)

notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)

Step 4 − Implement selector methods

@objc func foregroundCall() {
   print("App moved to foreground")
}
@objc func backgroundCall() {
   print("App moved to background!")
}

Step 5 − Put the breakpoint and run the application.

Complete code

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
      let notificationCenter = NotificationCenter.default
      notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)
      notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)
   }
   @objc func foregroundCall() {
      print("App moved to foreground")
   }
   @objc func backgroundCall() {
      print("App moved to background!")
   }
}

Updated on: 07-Aug-2019

547 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements