swiftui - 如何在 Apple Watch 的扩展委托中访问 SwiftUI 内容视图?
问题描述
当应用程序激活时,我需要打电话给loadData
我。是一个处理应用程序事件的类,例如. 但我不明白如何进入 ExtensionDelegate。ContentView
ExtensionDelegate
applicationDidBecomeActive
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")
}
推荐阅读
- slf4j - 始终记录 ID
- scala - 如何使用火花流从使用 scala 的 HBASE 表中获取数据
- swagger - 在 Swagger UI 中拦截消息
- ffmpeg - 使用 libav* 库实现 FFMpeg -r 和 -vf 之类的功能?
- c# - target=_blank 属性在文字字符串中不起作用
- php - Laravel/JWT token 什么时候被列入黑名单?
- java - 为什么我的 JavaFX 代码会出现 InvocationTargetException?
- java - 如何使用改造处理 JSON 对象中的 NULL 值
- xcode - Xcode Crash NO_CRASH_STACK + 0 没有堆栈跟踪和未符号化
- python - 如何生成用户所需的 JSON 文件