快速检测应用程序是在后台还是前台 [英] Detect if the application in background or foreground in swift

查看:25
本文介绍了快速检测应用程序是在后台还是前台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以知道我的应用程序是处于后台模式还是前台模式.谢谢

is there any way to know the state of my application if it is in background mode or in foreground . Thanks

推荐答案

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

[UIApplication sharedApplication].applicationState will return current state of applications such as:

  • UIApplicationStateActive
  • UIApplicationStateInactive
  • UIApplicationStateBackground

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

or if you want to access via notification see 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
}

这篇关于快速检测应用程序是在后台还是前台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆