有没有办法检查iOS应用程序是否在后台?

bob*_*ier 177 objective-c uiapplicationdelegate application-lifecycle ios ios-background-mode

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

在:

locationManagerDidUpdateLocation {
    if(app is runing in background){
        do this
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*idN 279

App委托获得指示状态转换的回调.您可以根据它进行跟踪.

此外,UIApplication中的applicationState属性返回当前状态.

[[UIApplication sharedApplication] applicationState]
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 - 为了更加清晰,它是[[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground. (64认同)
  • 我认为`[[UIApplication sharedApplication] applicationState]!= UIApplicationStateActive`更好,因为UIApplicationStateInactive几乎等同于后台... (39认同)
  • 各州都在这里详细说明:https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/c_ref/UIApplicationState (6认同)
  • 我发现,如果您的应用程序为了后台获取而生效,则不会调用转换回调. (2认同)

Asw*_*ose 172

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

这可以帮助您解决问题.

请参阅下面的评论 - 非活动是一个相当特殊的情况,可能意味着应用程序正处于启动到前台的过程中.根据你的目标,这可能意味着也可能意味着"背景"......


小智 27

斯威夫特3

    let state = UIApplication.shared.applicationState
    if state == .background {
        print("App in Background")
    }
Run Code Online (Sandbox Code Playgroud)


ioo*_*opl 18

Swift版本:

   let state = UIApplication.sharedApplication().applicationState
            if state == .Background {
                print("App in Background")
             }
Run Code Online (Sandbox Code Playgroud)


kli*_*mat 8

如果您希望接收回调而不是"询问"应用程序状态,请在以下方法中使用以下两种方法AppDelegate:

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


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


Sha*_*med 5

迅捷 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
    }
Run Code Online (Sandbox Code Playgroud)