ios-快速检测背景和前景中的应用程序

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

Mohammed Aboelwafa asked 2020-07-29T10:06:20Z
5个解决方案
102 votes

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

目标C

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
    // background
} else if (state == UIApplicationStateActive) {
    // foreground
}
Anbu.Karthik answered 2020-07-29T10:07:01Z
13 votes

迅捷3

  let state: UIApplicationState = UIApplication.shared.applicationState

            if state == .background {

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

                // foreground
            }
dimo hamdy answered 2020-07-29T10:07:20Z
4 votes

斯威夫特4

let state = UIApplication.shared.applicationState
        if state == .background {
            print("App in Background")
        }else if state == .active {
            print("App in Foreground or Active")
        }
Ashu answered 2020-07-29T10:07:40Z
2 votes

如果有人希望在Swift 3.0中

switch application.applicationState {
    case .active:
        //app is currently active, can update badges count here
        break
    case .inactive:
        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
        break
    case .background:
        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
        break
    default:
        break
    }

快速4

switch UIApplication.shared.applicationState {
case .active:
    //app is currently active, can update badges count here
    break
case .inactive:
    //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
    break
case .background:
    //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
    break
default:
    break
}
Hamid Shahsavari answered 2020-07-29T10:08:05Z
0 votes

您可以在应用程序进入后台或进入前台时添加一个布尔值。您可以通过使用App委托获得此信息。

根据Apple文档,也许您也可以使用应用程序的mainWindow属性或应用程序的活动状态属性。

NSApplication文档

讨论区 当应用的故事板或Nib文件尚未完成加载时,此属性中的值为nil。 当应用程序处于非活动状态或隐藏状态时,它也可能为零。

Atlandu answered 2020-07-29T10:08:39Z
translate from https://stackoverflow.com:/questions/38971994/detect-if-the-application-in-background-or-foreground-in-swift