简体   繁体   English

使用 SwiftUI 时如何检查应用程序是否在 Apple Watch 上进入后台

[英]How to check if an app enters background on Apple watch when using SwiftUI

I know for an iOS app, you can use something like我知道对于 iOS 应用程序,您可以使用类似

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        print("Moving to the background!")}

But I can not use willResignActiveNotification for WatchOS.但是我不能将 willResignActiveNotification 用于 WatchOS。 What should I do to detect if my watchOS app enters the background?我应该怎么做才能检测我的 watchOS 应用程序是否进入后台?

You need to use the WKExtensionDelegate methods to monitor WatchKit app lifecycle events.您需要使用WKExtensionDelegate方法来监控 WatchKit 应用程序生命周期事件。 There is no notification fired on these events, so you need to implement the applicationWillResignActive delegate method instead.这些事件不会触发任何通知,因此您需要改为实现applicationWillResignActive委托方法。 You can publish a custom notification from there and make your View listen to those notifications or simply create a custom Publisher that emits a value on WKExtensionDelegate method calls.您可以从那里发布自定义通知并使您的View侦听这些通知,或者简单地创建一个自定义Publisher ,该PublisherWKExtensionDelegate方法调用上发出一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM