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

时间:2020-06-14 10:58:00

标签: swiftui watchkit apple-watch

应用激活后,我需要在loadData中调用ContentViewExtensionDelegate是处理诸如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() {
    }
...

1 个答案:

答案 0 :(得分:1)

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

'stream does not contain image data or is null.'

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)
}