Reputation: 2098
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.
Upvotes: 28
Views: 25600
Reputation: 6924
[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:
e.g.
+(BOOL) runningInBackground
{
UIApplicationState state = [UIApplication sharedApplication].applicationState;
return state == UIApplicationStateBackground;
}
+(BOOL) runningInForeground
{
UIApplicationState state = [UIApplication sharedApplication].applicationState;
return state == UIApplicationStateActive;
}
Upvotes: 78
Reputation: 699
There are cases where checking the state does not work.
Here is one I ran into: If you try to use BT and it is disabled, iOS will bring up a dialog asking if the user would like to turn BT on. When this happens, the application state is not a reliable way to determine if your app is in the foreground.
First of all, you will get two applicationDidBecomeActive events - one (correctly) when the app appears and then another one (incorrectly) after the user presses the button in the dialog (while the iOS settings is the front-most app).
UIApplication.applicationState will say "Active" even though this is not the case (at least if you interpret "active" as being in the foreground, as was the original question).
Since you don't get willEnterForeground on first launch, the only reliable way of detecting if the app is visible or not (As far as I have been able to figure out) is to have a flag and then set it to true in:
applicationDidFinishLaunching
applicationWillEnterForeground
and false in:
applicationDidEnterBackground
applicationWillResignActive
Upvotes: 6