我想检查应用是否在后台运行。
在:
locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
答案 0 :(得分:274)
App委托获取指示状态转换的回调。您可以根据它进行跟踪。
UIApplication中的applicationState属性也返回当前状态。
[[UIApplication sharedApplication] applicationState]
答案 1 :(得分:173)
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
//Do checking here.
}
这可以帮助您解决问题。
请参阅下面的评论 - 非活动是一个相当特殊的情况,可能意味着该应用程序正处于启动进入前台的过程中。根据你的目标,这可能意味着或不意味着“背景”......
答案 2 :(得分:24)
Swift 3
let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}
答案 3 :(得分:18)
Swift版本:
let state = UIApplication.sharedApplication().applicationState
if state == .Background {
print("App in Background")
}
答案 4 :(得分:8)
如果您希望接收回调而不是"请问"关于应用程序状态,请在AppDelegate
:
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"app is actvie now");
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"app is not actvie now");
}
答案 5 :(得分:3)
swift 4
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
}
答案 6 :(得分:2)
快速4 +
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
}
答案 7 :(得分:1)
Swift 4.0扩展使其访问起来更简单:
import UIKit
extension UIApplication {
var isBackground: Bool {
return UIApplication.shared.applicationState == .background
}
}
要从您的应用内访问:
let myAppIsInBackground = UIApplication.isBackground
如果要查找有关各种状态(active
,inactive
和background
)的信息,则可以找到Apple documentation here。