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.
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.
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. You can read more in Activity.
You can see what apps you have running by going to the App Switcher. You can see what apps have access to Background App Refresh in Settings > General > Background App Refresh.
Inactive – The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received.
[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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With