首页 > 解决方案 > 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 的每个视图吗?

标签: swiftuistate-management

解决方案


推荐阅读