在Swift中检测应用程序是在后台还是前台运行

82

有没有办法知道我的应用程序是在后台模式还是前台模式下运行。谢谢。

有没有办法了解Android应用程序是否在前台或后台运行?


不知道具体情况,但当应用程序进入后台时,在appDelegate中的 func applicationDidEnterBackground(application: UIApplication) { } 你会接到调用。 - Sanchit Kumar Singh
6个回答

157

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

Objective C

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

1
@MohammedAboelwafa - 我修改了,检查一下更新后的答案。 - Anbu.Karthik
感谢 @Anbu.Karthik - Mohammed Aboelwafa
@MohammedAboelwafa 我的应用程序在表视图顶部有一个SegmentedControl。如果应用程序在前台,然后返回到后台(用户点击主页按钮),并且他在2天后再次点击应用程序。我应该在哪里检查应用程序的状态,ViewDidLoad是2天前初始化的,viewWillAppear将不会被调用。那么我该如何进行检查? - bibscy
@bibscy- 根据您的询问,苹果委托方法UIApplicationDidBecomeActive将被调用。 - Anbu.Karthik
即使应用程序可见,它仍然返回不活动。 - user924
@user924 - 这个能否附加视频? - Anbu.Karthik

18

Swift 3

  let state: UIApplicationState = UIApplication.shared.applicationState

            if state == .background {

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

                // foreground
            }

你能分享完整的代码吗?我们将在哪里测试这个函数? - Saleem Khan
@SaleemKhan 在任何你想要使用它的函数中,有时你需要知道应用程序是否在前台以使用相机拍照。 - dimohamdy
我想检查应用程序是否在后台运行,如果用户点击通知消息,则注销应用程序。因此,我想请您确认应用程序是否从后台视图中打开? - Saleem Khan
实际上,我们心中的背景和iOS的想法之间存在差异。请参见此链接:https://dev59.com/LGsz5IYBdhLWcg3wYGvQ#9508679 - Amir Shabani
即使应用程序可见(在viewDidLoad中),它仍然返回不活动状态。 - user924

13
在您的UIViewControllerviewDidload中使用这些观察器:
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

方法:

@objc func appMovedToBackground() {    
}

@objc func appMovedToForeground() {
}

8

Swift 4

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

3

如果有人需要使用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
    }

适用于Swift 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
}

1
你可以在应用程序进入后台或进入前台时添加一个布尔值。通过使用App delegate,您可以获得此信息。
根据苹果文档,您还可以使用应用程序的mainWindow属性或app的active状态属性。 NSApplication文档 讨论
当应用程序的故事板或nib文件尚未完成加载时,此属性中的值为nil。当应用程序处于非活动或隐藏状态时,它也可能为nil。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接