简体   繁体   English

watchOS-如何从扩展委托中更新SwiftUI视图

[英]watchOS - How to update a SwiftUI view from extension delegate

I have an independent watch app which tracks users calories throughout the day. 我有一个独立的手表应用程序,可以跟踪用户全天的卡路里。 So when I build and run the app for the first time through Xcode the onAppear(_:) method of the view is called and the calories are properly retrieved from the HealthKit repository. 因此,当我通过Xcode首次构建和运行该应用程序时,将调用该视图的onAppear(_:)方法,并且可以从HealthKit存储库中正确检索卡路里。

Whenever I put my hand down and raise my wrist after 5 min, the applicationDidBecomeActive of the ExtensionDelegate method is called but the onAppear(_:) method of the SwiftUI view is not getting called(my HealthKit code to fetch calories is called in this function) and the screen show's the same number of calories the previous time the app ran through Xcode. 每当我放下手并在5分钟后举起手腕时,都会调用ExtensionDelegate方法的applicationDidBecomeActive ,但不会调用SwiftUI视图的onAppear(_:)方法(此函数调用了我的HealthKit代码来获取卡路里) ),并且屏幕上一次在应用程序运行Xcode时显示的卡路里数相同。

Is this expected behaviour? 这是预期的行为吗? if yes then how can I update my SwiftUI view through the Extension Delegate? 如果是,那么如何通过扩展代理更新SwiftUI视图?

I think the failure to invoke .onAppear on wrist-raise is a bug, and I filed feedback about it. 我认为未能在手腕抬高上调用.onAppear是一个错误,我对此提出了反馈。 In the meantime, I got this to work as a "wrist-raise" event. 同时,我将其作为“举手”活动进行工作。

// ExtensionDelegate.swift

extension Notification.Name {
    static var applicationIsActive: Notification.Name {
      Notification.Name("applicationIsActive")
    }
}

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    func applicationDidBecomeActive() {
      NotificationCenter.default.post(name: .applicationIsActive, object: nil)
    }
}

// ContentView.swift

private var isActive = NotificationCenter.default.publisher(for: .applicationIsActive)

.onReceive(isActive) {_ in self.viewModel.refresh()}

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

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