Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an app is running in the foreground when a notification is received on iOS

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

like image 789
user1117453 Avatar asked Dec 27 '11 10:12

user1117453


People also ask

How do I know if an app is in foreground iOS?

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.

How do you know if an app moves to the background or foreground?

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.

In which state the app is running in the foreground and is receiving events?

Active - The app is running in the foreground, and receiving events.


3 Answers

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.

like image 68
DarkDust Avatar answered Oct 16 '22 23:10

DarkDust


Just to have a copy-paste code available for others:

if([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
    //App is in foreground. Act on it.
}
like image 21
Guntis Treulands Avatar answered Oct 16 '22 22:10

Guntis Treulands


Swift 5 version:

import UIKit
let isForeground = UIApplication.shared.applicationState == .active
like image 18
JanApotheker Avatar answered Oct 16 '22 22:10

JanApotheker