196

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

在:

locationManagerDidUpdateLocation {
    if(app is runing in background){
        do this
    }
}
4

8 回答 8

294

应用程序委托获取指示状态转换的回调。您可以根据它进行跟踪。

UIApplication中的applicationState属性也返回当前状态。

[[UIApplication sharedApplication] applicationState]
于 2011-04-29T18:24:35.407 回答
180
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
   //Do checking here.
}

这可以帮助您解决问题。

请参阅下面的评论 - 不活动是一个相当特殊的情况,可能意味着应用程序正在启动到前台。根据您的目标,这对您来说可能意味着也可能不意味着“背景”......

于 2013-02-05T06:42:45.537 回答
36

斯威夫特 3

    let state = UIApplication.shared.applicationState
    if state == .background {
        print("App in Background")
    }
于 2017-01-24T05:27:00.320 回答
24

斯威夫特版本:

let state = UIApplication.shared.applicationState
if state == .Background {
    print("App in Background")
}
于 2016-03-29T12:21:57.727 回答
8

如果您更喜欢接收回调而不是“询问”应用程序状态,请在您的AppDelegate:

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


- (void)applicationWillResignActive:(UIApplication *)application {
    NSLog(@"app is not actvie now");
}
于 2015-03-04T11:14:10.983 回答
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
    }
于 2018-04-24T11:30:57.467 回答
3

斯威夫特 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
        }
于 2019-09-11T07:53:27.637 回答
2

一个 Swift 4.0 扩展,使其更容易访问:

import UIKit

extension UIApplication {
    var isBackground: Bool {
        return UIApplication.shared.applicationState == .background
    }
}

要从您的应用程序中访问:

let myAppIsInBackground = UIApplication.shared.isBackground

如果您正在寻找有关各种状态(activeinactive)的信息background,您可以在此处找到 Apple 文档

于 2018-06-22T17:58:03.943 回答