SwiftUI解析JSON蓝牙烧烤探针温度数据界面无法显示问题求助
问题排查与解决方法
- 问题1:未触发数据加载
你编写的loadData网络请求方法没有调用入口,需要给页面根容器添加onAppear修饰符,在页面展示时自动触发请求:
var body: some View { VStack { // 原有界面代码 } .onAppear { loadData() } }
- 问题2:数据层级访问错误
你的数据是多层嵌套数组结构,不能直接用点语法访问数组内部属性,正确的层级关系如下:probeData([Meater]数组) → 取第一个Meater元素 → Meater的data属性 → data的devices([Devices]数组) → 取第一个Devices元素
界面访问示例:
List { if let firstProbe = probeData.first, let firstDevice = firstProbe.data.devices.first { Text("当前烹饪:\(firstDevice.cook.name)") .font(.system(size: 20)) .fontWeight(.light) .foregroundColor(.primary) Text("目标温度:\(String(firstDevice.cook.temperature.target)) ℃") .font(.callout) .fontWeight(.light) .foregroundColor(.primary) Text("内部温度:\(String(firstDevice.temperature.internal)) ℃") .font(.callout) .fontWeight(.light) .foregroundColor(.primary) Text("环境温度:\(String(firstDevice.temperature.ambient)) ℃") .font(.callout) .fontWeight(.light) .foregroundColor(.primary) Text("已耗时:\(firstDevice.cook.time.elapsed) 秒") .font(.system(size: 20)) .fontWeight(.light) .foregroundColor(.primary) Text("剩余时间:\(firstDevice.cook.time.remaining == -1 ? "计算中" : String(firstDevice.cook.time.remaining) + " 秒")") .font(.callout) .fontWeight(.light) .foregroundColor(.primary) } else { Text("正在加载探针数据...") } }
- 问题3:字符串插值语法错误
你把类型转换的as String写在了插值括号外面,属于语法错误,直接把数值转成String放在插值括号内即可,参考上面的示例代码。 - 可选优化:补充JSONDecoder配置
你的模型中updatedAt是Date类型,对应的JSON字段updated_at是秒级时间戳,建议解码时添加日期解析策略避免潜在的解码失败问题:
let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let decodedLists = try decoder.decode(Meater.self, from: d)
内容的提问来源于stack exchange,提问作者zeem
相关产品推荐
相关产品推荐

