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

chu*_*n26 3 apple-watch watchkit swiftui

当应用程序激活时我需要打电话loadData。是一个处理应用程序事件的类,例如. 但我不明白如何进入ExtensionDelegate。ContentViewExtensionDelegateapplicationDidBecomeActiveContentView

这是我的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)
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

ExtensionDelegate

class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {

    }

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

    func applicationWillResignActive() {
    }
...
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

我认为最简单的解决方案是使用通知

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()}
}
Run Code Online (Sandbox Code Playgroud)

并在ExtensionDelegate

func applicationDidBecomeActive() {
    NotificationCenter.default.post(name: .needsNetworkReload, object: nil)
}
Run Code Online (Sandbox Code Playgroud)

和共享的某个地方

extension Notification.Name {
    static let needsNetworkReload = Notification.Name("NeedsReload")
}
Run Code Online (Sandbox Code Playgroud)