我想检查应用程序是否在后台运行。
在:
locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
我想检查应用程序是否在后台运行。
在:
locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
应用程序委托(App Delegate)会得到回调,指示状态转换。您可以基于此跟踪它。
此外,UIApplication中的applicationState属性返回当前状态。
[[UIApplication sharedApplication] applicationState]
[[UIApplication sharedApplication] applicationState] != UIApplicationStateActive
更好,因为UIApplicationStateInactive几乎等同于处于后台... - JP IllanesUIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
//Do checking here.
}
这可能会帮助您解决问题。
请参见下面的评论 - “inactive”是一个相当特殊的情况,可能意味着应用程序正在被启动到前台。这可能或可能不意味着“后台”,具体取决于您的目标...
Swift 3
let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}
Swift版本:
let state = UIApplication.shared.applicationState
if state == .Background {
print("App in Background")
}
Swift 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
}
AppDelegate
中使用以下两种方法:- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"app is actvie now");
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"app is not actvie now");
}
Swift 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
}
import UIKit
extension UIApplication {
var isBackground: Bool {
return UIApplication.shared.applicationState == .background
}
}
let myAppIsInBackground = UIApplication.shared.isBackground
active
,inactive
和background
)的信息,您可以在苹果文档中找到。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
}
locationManager:didUpdateToLocation:fromLocation:
方法吗? - Black Frog