如何在 Apple Watch 的扩展委托中访问 SwiftUI 内容视图?

How to access to SwiftUI content view in extension delegate on Apple Watch?

当应用程序激活时,我需要在我的 ContentView 中调用 loadDataExtensionDelegate 是一个 class,它处理 applicationDidBecomeActive 等应用程序事件。但我不明白如何在 ExtensionDelegate 中获取 ContentView

这是我的 ContentView:

struct ContentView: View {

    let network = Network()

    @State private var currentIndex: Int = 0
    @State private var sources: [Source] = []

    var body: some View {
        ZStack {
            // Some view depends on 'sources'
        }
        .onAppear(perform: loadData)
    }

    func loadData() {
        network.getSources { response in
            switch response {
            case .result(let result):
                self.sources = result.results

            case .error(let error):
                print(error)
            }
        }
    }

}

ExtensionDelegate

class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {

    }

    func applicationDidBecomeActive() {
        // Here I need to call 'loadData' of my ContentView
    }

    func applicationWillResignActive() {
    }
...

据我所知,最简单的解决方案是使用通知

ContentView

let needsReloadNotification = NotificationCenter.default.publisher(for: .needsNetworkReload)

var body: some View {
    ZStack {
        // Some view depends on 'sources'
    }
    .onAppear(perform: loadData)
    .onReceive(needsReloadNotification) { _ in self.loadData()}
}

并在 ExtensionDelegate

func applicationDidBecomeActive() {
    NotificationCenter.default.post(name: .needsNetworkReload, object: nil)
}

和共享的某处

extension Notification.Name {
    static let needsNetworkReload = Notification.Name("NeedsReload")
}