iOS how to judge application is running foreground or background?

Smeegol picture Smeegol · Nov 28, 2011 · Viewed 24.4k times · Source

As we all knows, if an iOS app is running foreground, then the app won't notify users when the remove notification come. Now In my app, I want to show alert to notify users that remote notification comes. How to judge if the app is running foreground or background? I have found the docs and searched stackoverflow.com and failed to find any thing about that. Thank you.

Answer

Pavel Oganesyan picture Pavel Oganesyan · Nov 28, 2011

[UIApplication sharedApplication].applicationState will return current state, check it possible values and don't create unnecessary flags when you can use system features.

Values you may want to consider:

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

e.g.

+(BOOL) runningInBackground
{
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    return state == UIApplicationStateBackground;
}

+(BOOL) runningInForeground
{
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    return state == UIApplicationStateActive;
}