Search code examples
iosforeground

iOS how to judge application is running foreground or background?


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.


Solution

  • [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;
    }