一尘不染

快速检测应用程序是在后台还是在前台

swift

有什么方法可以知道我的应用程序的状态是后台模式还是前台模式。谢谢


阅读 274

收藏
2020-07-07

共1个答案

一尘不染

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

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

迅捷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
}

目标C

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
    // background
} else if (state == UIApplicationStateActive) {
    // foreground
}
2020-07-07