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

问题描述 投票:42回答:5

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

ios iphone swift swift3 lifecycle
5个回答
101
投票

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

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

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

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

13
投票

斯威夫特3

  let state: UIApplicationState = UIApplication.shared.applicationState

            if state == .background {

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

                // foreground
            }

4
投票

斯威夫特4

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

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
}

0
投票

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

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

NSApplication documentation

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

© www.soinside.com 2019 - 2024. All rights reserved.