如何创建WeatherKit的WeatherAlert示例用于SwiftUI视图预览?
如何创建WeatherKit的WeatherAlert示例用于SwiftUI预览?
因为WeatherAlert仅提供遵循Decodable协议的init(from:)初始化方法,你可以通过模拟JSON数据解码的方式创建预览用的实例,具体步骤如下:
方法1:用JSONDecoder解码模拟数据
- 准备符合
WeatherAlert结构的JSON模拟数据(可参考Apple官方文档中WeatherAlert的字段定义,或从真实接口返回的告警数据中提取片段) - 将JSON字符串转为Data,再用
JSONDecoder解码得到WeatherAlert实例
修改你的预览代码如下:
#Preview { // 模拟符合WeatherAlert结构的JSON数据 let mockAlertJSON = """ { "identifier": "test-alert-001", "sender": "National Weather Service", "headline": "Severe Thunderstorm Warning", "description": "Expect heavy rain and gusty winds through 6 PM local time.", "effectiveDate": "2024-05-20T14:00:00Z", "expirationDate": "2024-05-20T18:00:00Z", "severity": "severe", "certainty": "likely", "urgency": "immediate", "regions": ["King County"], "tags": ["thunderstorm", "wind"] } """.data(using: .utf8)! // 解码创建WeatherAlert实例(预览环境用try!安全,可确保模拟JSON结构匹配) let testAlert: WeatherAlert = try! JSONDecoder().decode(WeatherAlert.self, from: mockAlertJSON) return AlertView(alert: testAlert) }
提示:正式代码中建议用
do-catch处理解码错误,但预览场景下try!足够安全,因为你可以完全控制模拟JSON的结构准确性。
方法2:自定义Mock Decoder(进阶)
如果不想依赖JSON,可以自定义一个实现Decoder协议的Mock类,手动返回WeatherAlert所需的各个字段值,但这种方式代码量较大,仅在需要高度自定义模拟逻辑时使用。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

