let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
//MARK: - if you want to perform come action when app in background this will execute
//Handel you code here
}
else if state == .foreground{
//MARK: - if you want to perform come action when app in foreground this will execute
//Handel you code here
}
let appstate = UIApplication.shared.applicationState
switch appstate {
case .active:
print("the app is in active state")
case .background:
print("the app is in background state")
case .inactive:
print("the app is in inactive state")
default:
print("the default state")
break
}
switch UIApplication.shared.applicationState {
case .active:
print("App is active")
case .inactive:
print("App is inactive")
case .background:
print("App is in background")
default:
return
}
9条答案
按热度按时间ubby3x7f1#
应用程序委派会取得表示状态转换的回呼。您可以据此追踪它。
UIApplication中的applicationState属性也会传回目前的状态。
pu82cl6c2#
这可能有助于您解决问题。
看下面的评论--不活动是一个相当特殊的情况,可能意味着应用程序正在被启动到前台。这可能意味着你的目标是“后台”,也可能不意味着“后台”...
qf9go6mv3#
雨燕3
m1m5dgzv4#
Swift版本:
vyswwuz25#
雨燕5
epggiuax6#
如果您更喜欢接收回调而不是“询问”应用程序状态,请在
AppDelegate
中使用以下两个方法:ippsafx77#
斯威夫特4+
9gm1akwq8#
Swift 4.0扩展使访问它更容易:
若要从应用程序中访问:
如果要查找有关各种状态(
active
、inactive
和background
)的信息,可以找到Apple documentation here。q35jwt9p9#
感谢Shakeel Ahmed,这就是我在斯威夫特5中的工作
我希望它能帮助某人=)