1

在 iOS 13+ 中使用 SwiftUI 时,确定后台状态的传统方法不再适用。例如:

  • AppDelegate 方法applicationDidEnterBackground(_ application: UIApplication)applicationDidBecomeActive(_ application: UIApplication)不会被调用。

  • 通知didEnterBackgroundNotificationwillEnterForegroundNotificationdidBecomeActiveNotificationwillResignActiveNotification发送。

作为替代方案,还有UIWindowSceneDelegate回调:sceneDidBecomeActive(_ scene: UIScene), sceneWillResignActive(_ scene: UIScene), sceneWillEnterForeground(_ scene: UIScene),sceneDidEnterBackground(_ scene: UIScene)

这些替换的问题在于它们特定于进入和离开前景的多个场景之一。它们没有提供一种简单而干净的方法来确定整个应用程序是在前台还是后台。

由于与用户界面无关的原因,确定应用程序的前台/后台状态很重要。 当应用程序不在前台时,一些 iOS 功能会静默失败(通配符蓝牙扫描和 iBeacon 传输是两个例子。)我经常开发没有任何用户界面的 iOS 框架,所以我需要一种方法来确定应用程序的背景/前台状态不依赖于在其中粘贴一堆样板代码UIWindowSceneDelegate——我要求使用我的框架的人这样做是不合理的。

是否有任何直接的方法可以使用 SwiftUI 在 iOS 13 上确定应用程序的前台/后台状态?

4

2 回答 2

4

您也可以UIApplication在 SwiftUI 中使用通知:

  • didEnterBackgroundNotification
  • willEnterForegroundNotification
  • didBecomeActiveNotification
  • willResignActiveNotification

这是一个例子:

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in
    // active
}

NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { _ in
    // inactive
}
于 2020-09-09T21:07:05.890 回答
0

我相信在 SwiftUI 中处理事件的正确方法是使用onReceive方法。

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
        // Action
    }
于 2021-02-18T10:36:26.947 回答