37

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

Josh Brown
  • 52,385
  • 10
  • 54
  • 80
user1117453
  • 475
  • 1
  • 5
  • 8

3 Answers3

65

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.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • i want to know if anither app is running in foreground like camera or ipod or notes – user1117453 Dec 27 '11 at 12:59
  • So, what part of my answer do you have trouble with? If you read `[[UIApplication sharedApplication] applicationState]` it tells you whether your app is foreground or not. – DarkDust Dec 27 '11 at 13:07
  • Yes. this is for my app. how I would now exactly what app was before mine?IF was Camera for example or an appstore app? – user1117453 Dec 27 '11 at 14:26
  • 1
    There is no way to get this information. You only know whether your app is in foreground or not. – DarkDust Dec 27 '11 at 15:14
21

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

if([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
    //App is in foreground. Act on it.
}
Guntis Treulands
  • 4,764
  • 2
  • 50
  • 72
19

Swift 5 version:

import UIKit
let isForeground = UIApplication.shared.applicationState == .active
Renaud
  • 16,073
  • 6
  • 81
  • 79
JanApotheker
  • 1,746
  • 1
  • 17
  • 23
  • 3
    It's probably worth noting you need `import UIKit` since it's not obvious where the identifier `UIApplication` comes from. – SimpleJ Aug 28 '18 at 17:52