首页 > 解决方案 > 如何检测 swift 应用程序何时从后台进入前台?

问题描述

如果应用程序不是从后台运行,我想在我的应用程序中运行一个函数。我怎样才能做到这一点?

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

标签: swiftobservablelifecycle

解决方案


检查当前状态:

使用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.
}

推荐阅读