SwiftUI使用获取的数据更新全局状态

时间:2019-10-12 21:52:00

标签: swiftui state-management

我无法使用网络响应中的数据更新EnvironmentObject。在视图中,初始数据正确显示。我希望类调用API来更新响应的全局状态。然后我崩溃了

致命错误:未找到AppState类型的ObservableObject。

作为该视图的祖先,可能缺少AppState的View.environmentObject(_ :) 。:文件/BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-30.4/Core/EnvironmentObject。迅速行55#

filter

AppState声明:

>>> list(filter(lambda x: x["name"] in names_to_check, dictionaries))
[{'name': 'Koko', 'value': 1}, {'name': 'Bob', 'value': 4}]

发布将AppState环境对象附加到视图层次结构的结构。 我已将SceneDelegate中的AppState附加到ContentView作为我的根视图(如果我正确的话)

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的每个视图上吗?

0 个答案:

没有答案