How to detect if an iOS application is in background or foreground?

iOSiPhone/iPadMobile Development

To detect if an iOS application is in background or foreground we can simply use the UIApplication just like we can use it to detect many other things like battery state, status etc.

Let’s see how we can do this in our application. We’ll make use of shared resources of our Application which are stored in UIApplication.shared. We can use it like shown below −

print(UIApplication.shared.applicationState)

The shared.application state is an enum of type State, which consists of the following as per apple documentation.

public enum State : Int {
   case active
   case inactive
   case background
}

The case active means that the application is in the foreground and is receiving events like touch events or any other event that can keep the application active.

Case Inactive means that the application is running in the foreground but is not receiving any events.

Case background means that the application is running in the background.

We can use it according to our needs like shown above. We can also perform certain operations depending on conditions.

let state = UIApplication.shared.applicationState
if state == .active {
   print("I'm active")
}
else if state == .inactive {
   print("I'm inactive")
}
else if state == .background {
   print("I'm in background")
}

When we run this in viewDidLoad of our application we get the following result:

raja
Published on 30-Jan-2019 09:38:38
Advertisements