← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Shared/Capture/AppleWeather.swift (1747B)

1import CoreLocation
2import Foundation
3import WeatherKit
4
5/// Current conditions from WeatherKit, for a report's live context.
6enum AppleWeather {
7    private static let log = EventLog.shared.category("Weather")
8
9    /// The weather at `location` now, or `nil` if WeatherKit can't say.
10    /// Failures are logged: a missing entitlement or a service not yet
11    /// enabled for the App ID shows up here.
12    static func current(at location: CLLocation) async -> WeatherContext? {
13        do {
14            let current = try await WeatherService.shared.weather(for: location, including: .current)
15            return WeatherContext(current)
16        } catch {
17            log.error("Couldn't get the weather: \(error)")
18            return nil
19        }
20    }
21}
22
23extension WeatherContext {
24    /// Current conditions in the context's units: °C, hectopascals, km/h,
25    /// kilometres and fractions.
26    init(_ current: CurrentWeather) {
27        self.init(source: .weatherKit)
28        condition = current.condition.description
29        temperature = current.temperature.converted(to: .celsius).value
30        feelsLike = current.apparentTemperature.converted(to: .celsius).value
31        dewPoint = current.dewPoint.converted(to: .celsius).value
32        humidity = current.humidity
33        pressure = current.pressure.converted(to: .hectopascals).value
34        windSpeed = current.wind.speed.converted(to: .kilometersPerHour).value
35        windGust = current.wind.gust?.converted(to: .kilometersPerHour).value
36        windDirection = current.wind.direction.converted(to: .degrees).value
37        visibility = current.visibility.converted(to: .kilometers).value
38        uvIndex = Double(current.uvIndex.value)
39        cloudCover = current.cloudCover
40    }
41}