Files
onyx/Packages/OnyxKit/Sources/WeatherProvider/WeatherKitSource.swift
Guido Schmit 3d21cac3b7 Wetter: fehlende Ortungserlaubnis wird als solche benannt
"Wetter nicht abrufbar" war eine falsche Auskunft: abrufbar war es sehr wohl,
es fehlte nur die Erlaubnis. Derselbe Fehlertyp wie zuvor beim Kalender —
ein Zustand, den die App nicht kennt, landet im nächstbesten Sammelfall und
schickt den Nutzer damit in die Irre.

locationUndetermined ist jetzt ein eigener Zustand neben locationDenied. Der
Unterschied ist nicht kosmetisch: bei undetermined lohnt eine Anfrage, bei
denied fragt macOS nie wieder und es hilft nur der Weg über die
Systemeinstellungen oder ein fest gewählter Ort. Beide Fälle führen jetzt
dorthin, wo es weitergeht.

Die Anfrage kommt aus dem Berechtigungen-Reiter, nicht aus dem Hintergrund —
dieselbe Lehre wie beim Kalender: ohne Vordergrundfenster zeigt macOS keinen
Dialog, und die App wirkt kaputt, ohne dass irgendwo ein Fehler steht.

Aufgefallen war es daran, dass im Protokoll überhaupt kein Wetter-Eintrag
stand. Der einzige Pfad zu "nicht abrufbar" ohne Protokolleintrag war der
Standort — jetzt protokolliert auch der.
2026-08-10 20:45:49 +02:00

199 lines
7.6 KiB
Swift

import Foundation
import OSLog
import CoreLocation
import WeatherKit
private let log = Logger(subsystem: "com.scarriffleservices.onyx", category: "Weather")
/// Liefert den aktuellen Standort, oder sagt warum nicht.
///
/// Eigene Klasse statt eines Aufrufs mittendrin: `CLLocationManager` meldet
/// asynchron über einen Delegaten, und die Berechtigung kann sich jederzeit
/// ändern. Beides gehört an eine Stelle.
@MainActor
final class LocationProvider: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var pending: [CheckedContinuation<CLLocation?, Never>] = []
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyKilometer
}
var authorization: CLAuthorizationStatus { manager.authorizationStatus }
var isDenied: Bool {
authorization == .denied || authorization == .restricted
}
var isUndetermined: Bool { authorization == .notDetermined }
func requestAuthorization() {
guard authorization == .notDetermined else { return }
manager.requestWhenInUseAuthorization()
}
/// Eine einzelne Ortung. Liefert `nil`, wenn keine Berechtigung vorliegt
/// oder nichts hereinkommt.
func currentLocation() async -> CLLocation? {
guard !isDenied, !isUndetermined else { return nil }
if let cached = manager.location, cached.timestamp.timeIntervalSinceNow > -900 {
return cached
}
return await withCheckedContinuation { continuation in
pending.append(continuation)
manager.requestLocation()
}
}
private func resume(with location: CLLocation?) {
let waiting = pending
pending.removeAll()
waiting.forEach { $0.resume(returning: location) }
}
nonisolated func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
Task { @MainActor in self.resume(with: locations.last) }
}
nonisolated func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
Task { @MainActor in
log.error("Ortung fehlgeschlagen: \(error.localizedDescription, privacy: .public)")
self.resume(with: nil)
}
}
}
/// Wetter aus Apples WeatherKit.
@MainActor
public final class WeatherKitSource {
private let service = WeatherService.shared
private let location = LocationProvider()
private let geocoder = CLGeocoder()
public init() {}
public var locationIsDenied: Bool { location.isDenied }
public var locationIsUndetermined: Bool { location.isUndetermined }
public var locationIsAuthorized: Bool { !location.isDenied && !location.isUndetermined }
/// Fragt die Ortungsberechtigung an.
///
/// Muss aus einem Vordergrundfenster gerufen werden wie beim Kalender
/// zeigt macOS den Dialog sonst nicht an, und die App wirkt kaputt.
public func requestLocationAuthorization() { location.requestAuthorization() }
public func load(_ place: WeatherPlace) async -> WeatherState {
let coordinate: CLLocation
let placeName: String
switch place {
case .current:
if location.isUndetermined {
log.notice("Wetter: Ortungsberechtigung noch nicht erteilt")
return .locationUndetermined
}
guard let here = await location.currentLocation() else {
let denied = location.isDenied
log.error("Wetter: keine Ortung erhalten (verweigert: \(denied, privacy: .public))")
return denied
? .locationDenied
: .unavailable(lastKnown: nil, reason: "Standort nicht verfügbar")
}
coordinate = here
placeName = await name(for: here)
case .fixed(let name, let latitude, let longitude):
coordinate = CLLocation(latitude: latitude, longitude: longitude)
placeName = name
}
do {
let weather = try await service.weather(for: coordinate)
return .ready(Self.snapshot(from: weather,
placeName: placeName,
attribution: try? await attribution()))
} catch {
log.error("WeatherKit: \(error.localizedDescription, privacy: .public)")
return .unavailable(lastKnown: nil, reason: error.localizedDescription)
}
}
/// Apples Namensnennung. Keine Kür sie ist Bedingung der Nutzung.
private func attribution() async throws -> WeatherAttribution {
let legal = try await service.attribution
return WeatherAttribution(name: "Apple Weather",
legalPageURL: legal.legalPageURL,
logoURL: legal.combinedMarkDarkURL)
}
private func name(for location: CLLocation) async -> String {
guard let placemark = try? await geocoder.reverseGeocodeLocation(location).first else {
return "Aktueller Ort"
}
return placemark.locality ?? placemark.subAdministrativeArea
?? placemark.administrativeArea ?? "Aktueller Ort"
}
// MARK: - Umwandlung
private static func snapshot(from weather: Weather,
placeName: String,
attribution: WeatherAttribution?) -> WeatherSnapshot {
let current = weather.currentWeather
let today = weather.dailyForecast.first
return WeatherSnapshot(
placeName: placeName,
temperature: current.temperature,
apparentTemperature: current.apparentTemperature,
condition: map(current.condition),
isDaylight: current.isDaylight,
humidity: current.humidity,
windSpeed: current.wind.speed,
high: today?.highTemperature,
low: today?.lowTemperature,
hourly: weather.hourlyForecast.forecast
.filter { $0.date >= Date() }
.prefix(12)
.map {
HourlyPoint(date: $0.date,
temperature: $0.temperature,
condition: map($0.condition),
precipitationChance: $0.precipitationChance)
},
asOf: current.date,
attribution: attribution)
}
/// WeatherKit kennt deutlich mehr Lagen als hier unterschieden werden.
/// Feiner aufzulösen bringt nichts: das Widget hat ein Symbol und ein Wort
/// Platz, und mäßiger Sprühregen" liest dort niemand.
private static func map(_ condition: WeatherKit.WeatherCondition) -> WeatherCondition {
switch condition {
case .clear: .clear
case .mostlyClear: .mostlyClear
case .partlyCloudy, .mostlyCloudy: .partlyCloudy
case .cloudy: .cloudy
case .foggy, .haze, .smoky: .fog
case .drizzle, .freezingDrizzle: .drizzle
case .rain, .sunShowers, .freezingRain: .rain
case .heavyRain: .heavyRain
case .sleet, .wintryMix, .hail: .sleet
case .snow, .flurries, .sunFlurries, .blowingSnow: .snow
case .heavySnow, .blizzard: .heavySnow
case .thunderstorms, .isolatedThunderstorms, .scatteredThunderstorms,
.strongStorms, .tropicalStorm, .hurricane: .thunderstorm
case .windy, .breezy, .blowingDust: .windy
case .hot: .hot
case .frigid: .frigid
@unknown default: .unknown
}
}
}