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

时间:2020-08-20 11:24:19

标签: swift observable lifecycle

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

我不能使用applicationDidBecomeActive和applicationDidEnterBackground,因为我需要检测到它来自后台的情况,而不是要检测它进入后台或打开时的状态。 另外,当首次打开该应用程序时,它是从后台运行的。

2 个答案:

答案 0 :(得分:2)

您可能需要willEnterForegroundNotification

在应用离开背景状态之前不久发布 成为活动应用。

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

应用程序首次打开时,applicationStateinactive,当应用程序从后台启动时,applicationStatebackground

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

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

答案 1 :(得分:1)

检查当前状态:

使用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.
}
相关问题