检查iOS应用程序是否在后台

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

在:

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

应用程序委托获取指示状态转换的callback。 你可以根据它来跟踪它。

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

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

这可能会帮助你解决你的问题。

Swift版本:

  let state = UIApplication.sharedApplication().applicationState if state == .Background { print("App in Background") } 

Swift 3

  let state = UIApplication.shared.applicationState if state == .background { print("App in Background") } 

如果您更喜欢接收callback,而不是“询问”应用程序状态,请在AppDelegate使用这两种方法:

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