在swift中检测应用程序是背景还是前景

Moh*_*afa 46 iphone lifecycle ios swift swift3

有没有办法知道我的应用程序的状态,如果它处于后台模式或前台.谢谢

Anb*_*hik 106

[UIApplication sharedApplication].applicationState 将返回当前的应用程序状态,

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

或者如果您想通过通知访问,请参阅UIApplicationDidBecomeActiveNotification

我们需要打电话

迅速3及以上

let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
    // background
} else if state == .active {
    // foreground
}

switch UIApplication.shared.applicationState {
    case .background, .inactive:
        // background
    case .active:
        // foreground
    default:
        break
}
Run Code Online (Sandbox Code Playgroud)

另外一个选项 :

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
    // background
} else if (state == UIApplicationStateActive) {
    // foreground
}
Run Code Online (Sandbox Code Playgroud)

目标C.

let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
    // background
} else if state == .active {
    // foreground
}

switch UIApplication.shared.applicationState {
    case .background, .inactive:
        // background
    case .active:
        // foreground
    default:
        break
}
Run Code Online (Sandbox Code Playgroud)


dim*_*mdy 15

斯威夫特3

  let state: UIApplicationState = UIApplication.shared.applicationState

            if state == .background {

                // background
            }
            else if state == .active {

                // foreground
            }
Run Code Online (Sandbox Code Playgroud)


Mah*_*asi 14

viewDidload在您的以下方面使用这些观察者UIViewController

let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

和方法:

@objc func appMovedToBackground() {    
}

@objc func appMovedToForeground() {
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*shu 8

雨燕4

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