gpt4 book ai didi

ios - 将 EnvironmentObject 传递给 ObservableObject 类

转载 作者:行者123 更新时间:2023-12-05 02:07:59 27 4
gpt4 key购买 nike

<分区>

我制作了一个 SwiftUI 应用程序,它反复获取遥测数据以更新自定义 View 。 View 使用存储在 EnvironmentObject 中的变量。

struct updateEO{
@EnvironmentObject var settings:UserSettings
func pushSettingUpdate(telemetry: TelemetryData) {
settings.info = telemetry
print(settings.info)
}
}

class DownloadTimer : ObservableObject {
var timer : Timer!
let didChange = PassthroughSubject<DownloadTimer,Never>()
@Published var telemetry = TelemetryData()
func start() {
connectToClient()
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {
_ in
guard let url = URL(string: "http://127.0.0.1:25555/api/telemetry") else {
print("Invalid URL")
return
}

let request = URLRequest(url: url)

URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(TelemetryData.self, from: data) {
DispatchQueue.main.async {
updateEO().pushSettingUpdate(telemetry: decodedResponse)
}
return
}
}
}.resume()
}
}
}

在运行时,当遥测数据传递给 pushSettingUpdate(telemetry: decodedResponse) 时,应用程序崩溃并显示错误“ fatal error :未找到 UserSettings 类型的 ObservableObject。”。我知道我可能需要将结构传递给 EnvironmentObject,但我不确定该怎么做。任何帮助将非常感激。谢谢! :)

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com