Swift中Bundle解析hrv_data.json崩溃问题排查与解决
崩溃原因分析与解决方法
崩溃原因
- JSON结构与代码类型不匹配:代码中
RGB.rgbData被声明为[RGB](数组类型),但提供的JSON是单个RGB对象,并非数组格式。JSONDecoder尝试将单个对象解码为数组,直接导致解码失败。 - 错误信息无实际价值:
decode方法的错误处理中,打印的是Error.self(类型本身)而非实际捕获的错误实例,无法获取真实的解码失败原因,增加排查难度。
解决方法
1. 调整代码适配现有JSON结构
如果业务不需要数组格式,直接修改RGB的静态属性类型,匹配单个JSON对象:
struct RGB: Codable { let fps: Double let heartRate: Int let rgbValues: [RGBValue] static let sampleData: RGB = Bundle.main.decode(file: "hrv_data.json") }
2. 修改JSON为数组格式(若业务需要数组)
如果实际场景中需要处理多个RGB对象,将JSON包裹为数组:
[ { "fps": 0.1548667699098587, "heartRate": 81, "rgbValues": [ { "blue": 0, "green": 0, "timestamp": "22-04-2024 10:33:57", "red": 0 } ] } ]
3. 优化错误处理(建议必做)
修改Bundle的decode方法,捕获并打印真实错误,便于后续问题排查:
extension Bundle{ func decode<T: Decodable>(file: String) -> T { guard let url = self.url(forResource: file, withExtension: nil) else { fatalError("Could not find \(file) in the project!") } guard let data = try? Data(contentsOf: url) else { fatalError("Could not load \(file) in the project!") } let decoder = JSONDecoder() do { return try decoder.decode(T.self, from: data) } catch { fatalError("Could not decode \(file) in the project! Error: \(error)") } } }
内容的提问来源于stack exchange,提问作者Sourabh Garg
相关产品推荐
相关产品推荐

