You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建WeatherKit的WeatherAlert示例用于SwiftUI视图预览?

如何创建WeatherKit的WeatherAlert示例用于SwiftUI预览?

因为WeatherAlert仅提供遵循Decodable协议的init(from:)初始化方法,你可以通过模拟JSON数据解码的方式创建预览用的实例,具体步骤如下:

方法1:用JSONDecoder解码模拟数据

  1. 准备符合WeatherAlert结构的JSON模拟数据(可参考Apple官方文档中WeatherAlert的字段定义,或从真实接口返回的告警数据中提取片段)
  2. 将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:32:05