swiftui - 如何在 Apple Watch 的扩展委托(delegate)中访问 SwiftUI 内容 View ?

标签 swiftui watchkit apple-watch

当应用程序激活时,我需要在我的 ContentView 中调用 loadDataExtensionDelegate 是一个处理应用程序事件的类,例如 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")
}

关于swiftui - 如何在 Apple Watch 的扩展委托(delegate)中访问 SwiftUI 内容 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62371557/

相关文章:

ios - Xcode附加到进程不显示NSLog

ios - SwiftUI:对同一变量使用不同的属性包装器

ios - 相等的矩形动画不同?

ios - 如何在 WatchKit 扩展目标中获取核心数据持久存储路径

SwiftUI Apple Watch 应用程序在发布版本时崩溃(仅限系列 3)

ios - 为什么我会收到上传错误 ITMS-90680 和 ITMS-90171

ios - 如何使用swift2以编程方式获取Apple Watch序列号?

ios - WatchKit 数字输入控件?

swift - 为什么我在切换屏幕时会丢失我的 SwiftUI View

SwiftUI 表在 macOS Big Sur 上没有动画解雇