问题描述
如果应用程序不是从后台运行的,我想在我的应用程序中运行一个功能。我该怎么办?
我不能使用applicationDidBecomeActive和applicationDidEnterBackground,因为我需要检测到它来自后台的情况,而不是要检测它进入后台或打开时的状态。 另外,当首次打开该应用程序时,它是从后台运行的。
解决方法
您可能需要willEnterForegroundNotification。
在应用离开背景状态之前不久发布 成为活动应用。
请记住,第一次打开应用程序时,此通知在application(_:didFinishLaunchingWithOptions:)
之后发布。
应用程序首次打开时,applicationState
是inactive,当应用程序从后台启动时,applicationState
是background。
因此,您的代码将如下所示:
token = NotificationCenter.default.addObserver(
forName: UIApplication.willEnterForegroundNotification,object: nil,queue: .main
) { (notification: Notification) in
if UIApplication.shared.applicationState == .background {
// Came from the background
}
}
,
检查当前状态:
使用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.
}