Answers:
应用程序委托获取指示状态转换的回调。您可以基于此进行跟踪。
UIApplication中的applicationState属性也返回当前状态。
[[UIApplication sharedApplication] applicationState]
[[UIApplication sharedApplication] applicationState] != UIApplicationStateActive
更好,因为UIApplicationStateInactive几乎等同于处于后台...
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")
}
如果您希望接收回调而不是“询问”应用程序状态,请在您的中使用以下两种方法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
),你可以找到这里的苹果文档。
locationManager:didUpdateToLocation:fromLocation:
方法吗?