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

时间:2016-08-16 10:03:59

标签: ios iphone swift swift3 lifecycle

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

4 个答案:

答案 0 :(得分:13)

Swift 3

  let state: UIApplicationState = UIApplication.shared.applicationState

            if state == .background {

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

                // foreground
            }

答案 1 :(得分:4)

Swift 4

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

答案 2 :(得分:1)

如果有人希望在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
}

答案 3 :(得分:0)

当应用程序在后台输入或进入前景时,您可以添加布尔值。 您可以使用App委托获得此信息。

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

NSApplication documentation

  

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