如何检测 swift 应用程序何时从后台变为前台?

How can I detect when the swift application is foreground from the background?

我想 运行 我的应用程序中的一个功能,如果应用程序不是 运行 从后台运行的话。我该怎么做?

我不能使用applicationDidBecomeActive和applicationDidEnterBackground,因为我需要检测它来自后台时的情况,而不是它被带到后台或打开时的状态。 还有,第一次打开应用,后台来的时候是不行的。

查看当前状态:

使用UIApplication.shared.applicationState.

switch UIApplication.shared.applicationState {
case .active: // The app is running in the foreground and currently receiving events.
case .inactive: // The app is running in the foreground but is not receiving events. This might happen as a result of an interruption or because the app is transitioning to or from the background.
case .background: // The app is running in the background.
}

您可能需要 willEnterForegroundNotification.

Posted shortly before an app leaves the background state on its way to becoming the active app.

请记住,此通知是在首次打开应用程序时 application(_:didFinishLaunchingWithOptions:) 之后发布的。

首次打开应用程序时,applicationStateinactive and when the application comes from the background the applicationState is background

因此,您的代码将如下所示:

token = NotificationCenter.default.addObserver(
    forName: UIApplication.willEnterForegroundNotification,
    object: nil,
    queue: .main
) { (notification: Notification) in
    if UIApplication.shared.applicationState == .background {
        // Came from the background
    }
}