如何解决如何从后台检测swift应用程序何时为前台? 检查当前状态:
如果应用程序不是从后台运行的,我想在我的应用程序中运行一个功能。我该怎么办?
我不能使用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.
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。