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

use*_*194 4 lifecycle observable swift

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

我无法使用 applicationDidBecomeActive 和 applicationDidEnterBackground 因为我需要检测它来自后台时的情况,而不是它被带到后台或打开时的状态。另外,当应用程序第一次打开时,它来自后台时将无法工作。

Moj*_*ini 5

检查当前状态:

使用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.
}
Run Code Online (Sandbox Code Playgroud)