I would like to find a way to see what app is running in foreground or if the home screen is displayed when a local notification from my app show up. For example i want to have different actions if there is in homescreen or in someone else app. I tried to use processed and pid but the pid is generated hen the app starts and not the last time the app is used. Any idea? thanks
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. The shared. application state is an enum of type State, which consists of the following as per apple documentation.
The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed.
Active - The app is running in the foreground, and receiving events.
As described in the push notification documentation you can read [[UIApplication sharedApplication] applicationState]
when you receive the notification to determine whether your app is in foreground, inactive (it's visible but a dialog like the WiFi chooser is in front) or in background.
Just to have a copy-paste code available for others:
if([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
//App is in foreground. Act on it.
}
Swift 5 version:
import UIKit
let isForeground = UIApplication.shared.applicationState == .active
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With