我需要在应用程序启动时在loadData
中调用ContentView
。 ExtensionDelegate
是处理诸如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")
}