iOS如何判断应用程序是前台运行还是后台运行?
众所周知,如果iOS应用程序在前台运行,那么当删除通知到来时,该应用程序不会通知用户。现在在我的应用程序中,我想显示警报以通知用户远程通知到来。如何判断应用程序是前台运行还是后台运行?我找到了文档并搜索了 stackoverflow.com,但没有找到任何相关内容。 谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[UIApplication sharedApplication].applicationState
将返回当前状态,检查可能的值,并且在可以使用系统功能时不要创建不必要的标志。您可能需要考虑的值:
例如
[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.
在某些情况下,检查状态不起作用。
这是我遇到的一个问题:如果您尝试使用 BT,但它被禁用,iOS 会弹出一个对话框,询问用户是否要打开 BT。发生这种情况时,应用程序状态并不是确定应用程序是否位于前台的可靠方法。
首先,您将收到两个 applicationDidBecomeActive 事件 - 一个(正确地)在应用程序出现时发生,另一个(错误地)在用户按下对话框中的按钮后发生(而 iOS 设置是最前面的应用程序)。
UIApplication.applicationState 会说“Active”,即使情况并非如此(至少如果您将“active”解释为位于前台,就像最初的问题一样)。
由于您在第一次启动时没有得到 willEnterForeground ,因此检测应用程序是否可见的唯一可靠方法(据我所知)是有一个标志,然后将其设置为 true
:错误于:
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:
and false in: