在 iOS 上收到通知时确定应用程序是否在前台运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8643592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if an app is running in the foreground when a notification is received on iOS
提问by user1117453
I would like to find a way to see what app is running in foreground or if the home screen is displayed when a local notification from my app show up. For example i want to have different actions if there is in homescreen or in someone else app. I tried to use processed and pid but the pid is generated hen the app starts and not the last time the app is used. Any idea? thanks
我想找到一种方法来查看哪些应用程序在前台运行,或者当我的应用程序显示本地通知时是否显示主屏幕。例如,如果在主屏幕或其他应用程序中,我想有不同的操作。我尝试使用处理过的和 pid 但 pid 是在应用程序启动时生成的,而不是最后一次使用应用程序时生成的。任何的想法?谢谢
回答by DarkDust
As described in the push notification documentationyou can read [[UIApplication sharedApplication] applicationState]
when you receive the notification to determine whether your app is in foreground, inactive (it's visible but a dialog like the WiFi chooser is in front) or in background.
如推送通知文档中所述,您可以[[UIApplication sharedApplication] applicationState]
在收到通知时阅读,以确定您的应用程序是处于前台、非活动状态(它是可见的,但像 WiFi 选择器这样的对话框在前面)还是在后台。
回答by Guntis Treulands
Just to have a copy-paste code available for others:
只是为了让其他人可以使用复制粘贴代码:
if([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
//App is in foreground. Act on it.
}
回答by JanApotheker
Swift 5 version:
斯威夫特 5 版本:
import UIKit
let isForeground = UIApplication.shared.applicationState == .active