我想检查应用程序是否在后台运行。
在:
locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
我想检查应用程序是否在后台运行。
在:
locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
应用程序委托获取指示状态转换的回调。您可以根据它进行跟踪。
UIApplication中的applicationState属性也返回当前状态。
[[UIApplication sharedApplication] applicationState]
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
//Do checking here.
}
这可以帮助您解决问题。
请参阅下面的评论 - 不活动是一个相当特殊的情况,可能意味着应用程序正在启动到前台。根据您的目标,这对您来说可能意味着也可能不意味着“背景”......
斯威夫特 3
let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}
斯威夫特版本:
let state = UIApplication.shared.applicationState
if state == .Background {
print("App in Background")
}
如果您更喜欢接收回调而不是“询问”应用程序状态,请在您的AppDelegate
:
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"app is actvie now");
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"app is not actvie now");
}
迅速 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
}
斯威夫特 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
}
一个 Swift 4.0 扩展,使其更容易访问:
import UIKit
extension UIApplication {
var isBackground: Bool {
return UIApplication.shared.applicationState == .background
}
}
要从您的应用程序中访问:
let myAppIsInBackground = UIApplication.shared.isBackground
如果您正在寻找有关各种状态(active
和inactive
)的信息background
,您可以在此处找到 Apple 文档。