Is there any way to check if iOS app is in background?

随声附和 提交于 2019-11-27 17:28:25
DavidN

App delegate gets callbacks indicating state transitions. You can track it based on that.

Also the applicationState property in UIApplication returns the current state.

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

This may help you in solving your problem.

See comment below - inactive is a fairly special case, and can mean that the app is in the process of being launched into the foreground. That may or may not mean "background" to you depending on your goal...

Swift 3

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

Swift version :

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

If you prefer to receive callbacks instead of "ask" about the application state, use these two methods in your AppDelegate:

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


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

swift 4

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
    }
CodeBender

A Swift 4.0 extension to make accessing it a bit easier:

import UIKit

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

To access from within your app:

let myAppIsInBackground = UIApplication.shared.isBackground

If you are looking for information on the various states (active, inactive and background), you can find the Apple documentation here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!