有什么方法可以检查iOS应用是否在后台?

| 我想检查应用程序是否在后台运行。 在:
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.sharedApplication().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文档。     

要回复问题请先登录注册