WeatherKit历史数据获取及归属标识深色模式适配问题咨询
WeatherKit 两个问题的解决方案
1. 历史天气数据接入方法
WeatherKit 正式版已经支持历史天气查询,就是WWDC相关Session提到的带日期参数的接口,不需要额外申请权限,直接调用 WeatherService 的对应重载方法即可,使用时注意几个规则:
- 可查询的时间范围为当前时间往前推10年,不支持查询超出该范围的历史数据
- 单次请求的时间区间最长不能超过31天,如果需要查询更长时间范围的历史数据,拆分多次请求即可
- 可以按需指定要查询的数据集(比如日维度历史数据、小时维度历史数据),减少不必要的流量开销
调用示例代码:
// 定义查询位置和时间范围 let targetLocation = CLLocation(latitude: 37.77, longitude: -122.41) // 例:查询2024年5月1日至5月7日的日维度历史数据 let start = Calendar.current.date(from: DateComponents(year: 2024, month: 5, day: 1))! let end = Calendar.current.date(from: DateComponents(year: 2024, month: 5, day: 7))! do { let historicalResult = try await WeatherService.shared.weather( for: targetLocation, including: .daily(startDate: start, endDate: end) ) // 遍历处理返回的历史日序数据 for dayWeather in historicalResult.forecast { print(dayWeather.date, dayWeather.highTemperature, dayWeather.lowTemperature) } } catch { print("历史天气请求失败:\(error.localizedDescription)") }
如果需要小时级的历史数据,把including参数换成.hourly(startDate: start, endDate: end)即可。
2. 深色模式下归属Logo显示白块的修复
你遇到的问题由两个原因共同导致:
- 你当前写的获取归属信息的
.task没有绑定深浅模式状态,只会在视图首次加载时执行一次,切换模式时不会自动拉取对应配色的Logo地址 - iOS 16初始Beta版的AsyncImage加载WeatherKit提供的Logo素材时,会默认把带透明通道的PNG/PDF素材当模板图渲染,同时丢失透明通道,导致透明区域被填充为白色
修复步骤:
- 给获取归属信息的
.task绑定colorScheme作为id,这样系统检测到深浅模式切换时,会自动重新执行任务拉取对应配色的Logo地址 - 自定义AsyncImage的加载逻辑,强制指定图片用原始渲染模式,不要用模板渲染,同时给Logo设置固定的展示尺寸,避免Beta版的渲染尺寸异常
修复后的归属模块代码:
// 替换你原来的AsyncImage代码 AsyncImage(url: attLogo) { loadPhase in switch loadPhase { case .success(let logoImage): logoImage .resizable() .renderingMode(.original) // 关键:强制使用原始素材渲染,禁止系统自动着色 .scaledToFit() .frame(height: 30) // 给Logo设置固定高度,避免渲染变形 case .failure: // 加载失败时可以展示兜底的文字归属说明 Text("数据来源:Apple Weather") .font(.footnote) case .empty: ProgressView() @unknown default: EmptyView() } } // 替换你原来的获取归属信息的task,绑定colorScheme作为id .task(id: colorScheme) { do { let weatherAttribution = try await WeatherService.shared.attribution attributionURL = weatherAttribution.legalPageURL // 浅色模式用深色Logo,深色模式用浅色Logo attLogo = colorScheme == .light ? weatherAttribution.combinedMarkDarkURL : weatherAttribution.combinedMarkLightURL } catch { print("归属信息加载失败") } }
额外说明:你当前使用的Xcode 14.0 Beta、iOS 16初始测试版本身就存在WeatherKit素材渲染的已知bug,升级到Xcode 14正式版、iOS 16.0正式版及以上系统后,配合上面的代码修改,白块问题会完全消失。
内容的提问来源于stack exchange,提问作者JohnSF
相关产品推荐
相关产品推荐

