swiftui - SwiftUI 使用获取的数据更新全局状态
问题描述
我无法使用来自网络响应的数据更新 EnvironmentObject。在视图中,初始数据显示正常。我希望类调用 API 以响应更新全局状态。然后我遇到了崩溃
致命错误:未找到 AppState 类型的 ObservableObject。
AppState 的 View.environmentObject(_:) 作为此视图的祖先可能会丢失。:文件 /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-30.4/Core/EnvironmentObject.swift,行55#
struct GameView: View {
var location = LocationService()
@EnvironmentObject var appState: AppState
var body: some View {
VStack{
Text("countryRegion: \(self.appState.countryRegion)")
Text("adminDistrict: \(self.appState.adminDistrict)")
}.onAppear(perform: startMonitoring)
}
func startMonitoring() {
self.appState.isGameActive = true
self.location.startMonitoringLocation()
}
}
class LocationService: NSObject, CLLocationManagerDelegate{
@EnvironmentObject var appState: AppState
...
func getAddress(longitude: CLLocationDegrees, latitude: CLLocationDegrees) {
let url = URL(string: "http://dev.virtualearth.net/REST/v1/Locations/\(latitude),\(longitude)?o=json&key=\(self.key)")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
let response = try! JSONDecoder().decode(Results.self, from: data)
DispatchQueue.main.async {
self.appState.adminDistrict = response.resourceSets[0].resources[0].address.adminDistrict;
self.appState.countryRegion = response.resourceSets[0].resources[0].address.countryRegion;
}
}.resume()
}
AppState 声明:
class AppState: ObservableObject {
@Published var isGameActive = false
@Published var countryRegion = ""
@Published var adminDistrict = ""
}
发布将 AppState 环境对象附加到视图层次结构的结构。 我已将 SceneDelegate 中的 AppState 附加到 ContentView 作为我的根视图(如果我做对了)
window.rootViewController = UIHostingController(rootView:ContentView().environmentObject(appState))
我应该将它附加到修改 AppState 的每个视图吗?
解决方案
推荐阅读
- regex - 如何在 MongoDb 上查询字段不包含字符串
- c# - 仅将 ReSharper 配置为为非原始类型推荐“var”?
- wordpress - WordPress 白屏或 https 上的内存限制
- c# - 使用授权标头重定向到操作
- xamarin.forms - 仅适用于 iOS 真实设备的 Xamain.Forms 中 api 调用的任务取消异常
- javascript - Ref 只获取最后一个元素 - VueJS
- php - Clarifai 搜索(curl)如何在每次调用中获取更多图像
- java - JDateChooser 上的 propertychangelistener 会额外触发 2 次,即使在以编程方式设置日期时分离了侦听器也是如此
- sharepoint - PowerApps 库未为用户显示 SharePoint 数据
- java - 为什么我的原始类型参数方法不覆盖包装器类型参数超类方法?