SwiftUI中用WeatherKit判断当日是否降雨及获取下一小时预报
基于WeatherKit的两个功能实现方案
一、判断当日是否会降雨(含毛毛雨、雷暴等)
核心思路是遍历当日所有小时的天气预报,检查是否存在降雨类天气状况。WeatherKit的WeatherCondition枚举包含了所有降雨相关的case(如.rain, .drizzle, .thunderstorm等),通过判断小时预报的condition是否属于这类即可确定当日是否有降雨。
实现代码
import WeatherKit import CoreLocation func willRainToday(for location: CLLocation) async -> Bool { let weatherService = WeatherService.shared do { let hourlyForecast = try await weatherService.hourlyWeather(for: location) // 筛选当日的小时预报 let todayStart = Calendar.current.startOfDay(for: Date()) let todayEnd = Calendar.current.date(byAdding: .day, value: 1, to: todayStart)! let todayForecasts = hourlyForecast.filter { $0.date >= todayStart && $0.date < todayEnd } // 定义所有降雨类天气类型 let rainRelatedConditions: Set<WeatherCondition> = [ .rain, .drizzle, .thunderstorm, .freezingRain, .freezingDrizzle ] // 判断是否存在降雨类天气 return todayForecasts.contains { rainRelatedConditions.contains($0.condition) } } catch { print("获取小时预报失败: \(error.localizedDescription)") return false } }
调用示例(SwiftUI视图中可通过Task执行):
Task { let targetLocation = CLLocation(latitude: 31.23, longitude: 121.47) // 替换为目标位置 let hasRain = await willRainToday(for: targetLocation) print("今日是否有降雨: \(hasRain)") }
二、获取当前时间的下一小时天气状况
通过筛选小时预报数组,找到当前时间之后的第一个小时预报条目,从中提取符号名称和温度即可。
实现代码
func nextHourWeather(for location: CLLocation) async -> (symbolName: String, temperature: String)? { let weatherService = WeatherService.shared do { let hourlyForecast = try await weatherService.hourlyWeather(for: location) let now = Date() // 找到当前时间之后的第一个小时预报 guard let nextHourForecast = hourlyForecast.first(where: { $0.date > now }) else { return nil } // 格式化温度为可读字符串 let tempFormatter = MeasurementFormatter() tempFormatter.unitStyle = .short let tempString = tempFormatter.string(from: nextHourForecast.temperature) return (nextHourForecast.symbolName, tempString) } catch { print("获取小时预报失败: \(error.localizedDescription)") return nil } }
调用示例:
Task { let targetLocation = CLLocation(latitude: 31.23, longitude: 121.47) if let nextHourData = await nextHourWeather(for: targetLocation) { print("下一小时天气符号: \(nextHourData.symbolName),温度: \(nextHourData.temperature)") } }
注意事项
- 确保项目已配置WeatherKit权限:在
Info.plist中添加NSLocationWhenInUseUsageDescription(位置权限说明),并在Xcode的Signing & Capabilities中添加WeatherKit服务。 - 若已有获取天气的逻辑,可将上述代码整合到现有函数中,避免重复创建
WeatherService实例。
内容的提问来源于stack exchange,提问作者helloimbrando
相关产品推荐
相关产品推荐

