有什么方法来检查 iOS 应用程序是否在后台运行?

我想检查应用程序是否在后台运行。

:

locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
97224 次浏览

应用程序委托获得指示状态转换的回调。你可以根据这个来追踪它。

UIApplication中的applicationState属性返回当前状态。

[[UIApplication sharedApplication] applicationState]
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
//Do checking here.
}

这可能会帮助你解决问题。

请参见下面的评论- inactive是一个相当特殊的情况,这可能意味着应用程序正在被启动到前台。根据你的目标,这对你来说可能意味着“背景”,也可能不意味着“背景”。

如果你更喜欢接收回调而不是“询问”应用程序状态,可以在AppDelegate中使用以下两个方法:

- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"app is actvie now");
}




- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"app is not actvie now");
}

Swift版本:

let state = UIApplication.shared.applicationState
if state == .Background {
print("App in Background")
}

斯威夫特3

    let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}

斯威夫特5

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
}

一个Swift 4.0扩展,使访问它更容易一点:

import UIKit


extension UIApplication {
var isBackground: Bool {
return UIApplication.shared.applicationState == .background
}
}

从你的应用程序中访问:

let myAppIsInBackground = UIApplication.shared.isBackground

如果你正在寻找关于各种状态(activeinactivebackground)的信息,你可以找到苹果文档在这里

斯威夫特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
}

感谢Shakeel Ahmed,这是我在Swift 5中所使用的方法

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
}

我希望它能帮助到别人=)