如何在SwiftUI中从WeatherKit获取最低和最高气温?
解决WeatherKit获取当日最低/最高气温的问题
问题原因
你调用currentWeather.lowTemperature和currentWeather.highTemperature无效,是因为CurrentWeather仅包含当前时刻的天气数据,并不提供当日气温极值。这类数据属于**每日预报(DailyWeather)**的范畴。
正确实现方案
1. 请求包含每日预报的天气数据
调用WeatherKit接口时,需明确指定包含.daily类型的预报:
import WeatherKit import CoreLocation let weatherService = WeatherService.shared let targetLocation = CLLocation(latitude: 你的纬度值, longitude: 你的经度值) Task { do { // 请求包含每日预报的天气数据 let weather = try await weatherService.weather(for: targetLocation, including: .daily) // 后续处理每日预报数据 } catch { print("天气数据获取失败:\(error.localizedDescription)") } }
2. 提取当日的最低/最高气温
从dailyForecast的第一个元素(对应当日预报)中读取气温极值:
if let todayForecast = weather.dailyForecast.first { let lowTemp = todayForecast.lowTemperature let highTemp = todayForecast.highTemperature // 适配Complication的文本展示(可根据需求调整单位和格式) Text("L: \(lowTemp.converted(to: .celsius).formatted(.number.precision(.fractionLength(0))))° H: \(highTemp.converted(to: .celsius).formatted(.number.precision(.fractionLength(0))))°") } else { Text("暂无气温数据") }
3. 适配Complication场景
在Complication的TimelineProvider实现中,确保请求WeatherKit数据时包含每日预报,并将提取的高低温数据传入Complication视图组件,完成数据绑定。
关键提示
DailyWeather类型原生提供lowTemperature和highTemperature属性,直接对应当日气温极值。- 可通过
converted(to:)方法根据用户偏好切换摄氏度/华氏度。 - 必须处理
dailyForecast为空的情况,避免Complication显示异常。
内容的提问来源于stack exchange,提问作者Aadish123
相关产品推荐
相关产品推荐

