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

问题描述 投票:0回答:1

我需要在应用程序启动时在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() {
    }
...
swiftui watchkit apple-watch
1个回答
0
投票

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

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")
}
    
© www.soinside.com 2019 - 2024. All rights reserved.