iOS how to judge application is running foreground or background?

房东的猫 提交于 2019-11-27 11:11:17

问题


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.


回答1:


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



回答2:


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 


来源:https://stackoverflow.com/questions/8291192/ios-how-to-judge-application-is-running-foreground-or-background

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!