Wetter: Zwischenspeicher auf Platte, Zeitlimits auf alle Netzaufrufe
Das Protokoll zeigte das Wetter nach 185 ms erfolgreich geladen — und danach nichts mehr. Dazwischen liegt genau ein Aufruf, der noch ins Netz geht: die Abfrage der Namensnennung. Sie hatte kein Zeitlimit, und ohne sie wurde der Schnappschuss nie gebaut. Ein Netzaufruf ohne Zeitlimit ist ein Aufruf, der hängen darf. Jetzt hat jeder ein Limit: Wetter zwölf Sekunden, Ortung acht, Umkehrsuche fünf, Namensnennung drei. Die Namensnennung hält den Messwert ohnehin nicht mehr auf — sie ist Pflicht für die Anzeige, nicht für das Laden — und wird behalten, weil sie sich nicht ändert. Der Zwischenspeicher lag nur im Arbeitsspeicher. Beim Start stand deshalb ein Rädchen da, bis der erste Abruf durch war; hing der, für immer. Er liegt jetzt in weather.json und wird beim Anlegen des Modells gelesen: das Widget zeigt sofort, was zuletzt bekannt war, mit Zeitstempel, und lädt im Hintergrund nach. Ein Wert von vor einer Stunde ist eine Auskunft, ein Rädchen ist keine. Nachgeprüft: Datei wird geschrieben, Hamburg mit zwölf Stundenwerten. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,22 @@
|
||||
{
|
||||
"sourceLanguage": "en",
|
||||
"strings": {
|
||||
"weather.error.timeout": {
|
||||
"localizations": {
|
||||
"de": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Zeitüberschreitung beim Abruf"
|
||||
}
|
||||
},
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Request timed out"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"widget.weather.asOf": {
|
||||
"comment": "%@ ist die Uhrzeit des Messwerts",
|
||||
"localizations": {
|
||||
|
||||
@@ -12,8 +12,32 @@ public struct WeatherCache: Sendable {
|
||||
public static let maxAge: TimeInterval = 15 * 60
|
||||
|
||||
private var entries: [String: WeatherSnapshot] = [:]
|
||||
private let url: URL?
|
||||
|
||||
public init() {}
|
||||
/// Liest beim Anlegen, was zuletzt bekannt war.
|
||||
///
|
||||
/// Der Zwischenspeicher liegt auf der Platte und nicht nur im Arbeits-
|
||||
/// speicher: sonst steht beim Start ein Rädchen da, bis der erste Abruf
|
||||
/// durch ist — und wenn der hängt, für immer. Ein Wert von vor einer
|
||||
/// Stunde mit Zeitstempel ist die bessere Auskunft.
|
||||
public init(url: URL? = WeatherCache.standardURL) {
|
||||
self.url = url
|
||||
guard let url, let data = try? Data(contentsOf: url) else { return }
|
||||
// Eine unlesbare Datei ist kein Grund, das Widget aufzugeben.
|
||||
entries = (try? JSONDecoder().decode([String: WeatherSnapshot].self, from: data)) ?? [:]
|
||||
}
|
||||
|
||||
public static var standardURL: URL? {
|
||||
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
|
||||
.appendingPathComponent("Onyx/weather.json")
|
||||
}
|
||||
|
||||
public func save() throws {
|
||||
guard let url else { return }
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(entries).write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
/// Der Stand, wenn er noch frisch genug ist.
|
||||
public func valid(for place: WeatherPlace, now: Date = Date()) -> WeatherSnapshot? {
|
||||
@@ -77,3 +101,23 @@ public extension WeatherCondition {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Führt einen Aufruf mit Zeitlimit aus.
|
||||
///
|
||||
/// WeatherKit hat keines. Beim Testen lieferte es das Wetter in 185 ms und
|
||||
/// blieb danach beim Abruf der Namensnennung stehen — das Widget zeigte für
|
||||
/// immer ein Rädchen. Ein Netzaufruf ohne Zeitlimit ist ein Aufruf, der
|
||||
/// hängen darf.
|
||||
func withTimeout<T: Sendable>(seconds: TimeInterval,
|
||||
operation: @escaping @Sendable () async -> T) async -> T? {
|
||||
await withTaskGroup(of: T?.self) { group in
|
||||
group.addTask { await operation() }
|
||||
group.addTask {
|
||||
try? await Task.sleep(for: .seconds(seconds))
|
||||
return nil
|
||||
}
|
||||
let first = await group.next() ?? nil
|
||||
group.cancelAll()
|
||||
return first
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,8 @@ public final class WeatherKitSource {
|
||||
|
||||
private let service = WeatherService.shared
|
||||
private let location = LocationProvider()
|
||||
private let geocoder = CLGeocoder()
|
||||
/// Einmal geholt, dann behalten — sie ändert sich nicht.
|
||||
private var cachedAttribution: WeatherAttribution?
|
||||
|
||||
public init() {}
|
||||
|
||||
@@ -114,7 +115,11 @@ public final class WeatherKitSource {
|
||||
log.notice("Wetter: Ortungsberechtigung noch nicht erteilt")
|
||||
return .locationUndetermined
|
||||
}
|
||||
guard let here = await location.currentLocation() else {
|
||||
// Zeitlimit: CoreLocation kann auf eine Ortung warten, die nie
|
||||
// kommt — etwa ohne Sicht auf WLAN-Netze.
|
||||
guard let here = await withTimeout(seconds: 8, operation: {
|
||||
await self.location.currentLocation()
|
||||
}) ?? nil else {
|
||||
let denied = location.isDenied
|
||||
log.error("Wetter: keine Ortung erhalten (verweigert: \(denied, privacy: .public))")
|
||||
return denied
|
||||
@@ -129,27 +134,54 @@ public final class WeatherKitSource {
|
||||
placeName = name
|
||||
}
|
||||
|
||||
do {
|
||||
let weather = try await service.weather(for: coordinate)
|
||||
let service = self.service
|
||||
let fetched = await withTimeout(seconds: 12) { () -> Result<Weather, Error> in
|
||||
do { return .success(try await service.weather(for: coordinate)) }
|
||||
catch { return .failure(error) }
|
||||
}
|
||||
|
||||
switch fetched {
|
||||
case .success(let weather):
|
||||
return .ready(Self.snapshot(from: weather,
|
||||
placeName: placeName,
|
||||
attribution: try? await attribution()))
|
||||
} catch {
|
||||
attribution: await attribution()))
|
||||
case .failure(let error):
|
||||
log.error("WeatherKit: \(error.localizedDescription, privacy: .public)")
|
||||
return .unavailable(lastKnown: nil, reason: error.localizedDescription)
|
||||
case nil:
|
||||
log.error("WeatherKit: Zeitlimit überschritten")
|
||||
return .unavailable(lastKnown: nil, reason: String(
|
||||
localized: "weather.error.timeout", bundle: .module))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
///
|
||||
/// Aber sie darf den Wetterwert nicht aufhalten. Genau daran hing das
|
||||
/// Widget: das Wetter war in 185 ms da, und dieser Aufruf kam nie zurück.
|
||||
/// Also mit knappem Zeitlimit, und das Ergebnis wird behalten — die
|
||||
/// Namensnennung ändert sich nicht.
|
||||
private func attribution() async -> WeatherAttribution? {
|
||||
if let cachedAttribution { return cachedAttribution }
|
||||
let service = self.service
|
||||
let fetched = await withTimeout(seconds: 3) { () -> WeatherAttribution? in
|
||||
guard let legal = try? await service.attribution else { return nil }
|
||||
return WeatherAttribution(name: "Apple Weather",
|
||||
legalPageURL: legal.legalPageURL,
|
||||
logoURL: legal.combinedMarkDarkURL)
|
||||
} ?? nil
|
||||
cachedAttribution = fetched
|
||||
return fetched
|
||||
}
|
||||
|
||||
private func name(for location: CLLocation) async -> String {
|
||||
guard let placemark = try? await geocoder.reverseGeocodeLocation(location).first else {
|
||||
// Auch hier ein Zeitlimit: ohne Netz wartet die Umkehrsuche lange.
|
||||
// `CLGeocoder` ist nicht `Sendable`, also wird es im Aufruf angelegt
|
||||
// statt eingefangen — es dient ohnehin nur diesem einen Zweck.
|
||||
let found = await withTimeout(seconds: 5) {
|
||||
try? await CLGeocoder().reverseGeocodeLocation(location).first
|
||||
} ?? nil
|
||||
guard let placemark = found else {
|
||||
return "Aktueller Ort"
|
||||
}
|
||||
return placemark.locality ?? placemark.subAdministrativeArea
|
||||
|
||||
@@ -6,7 +6,7 @@ import Foundation
|
||||
/// gegen ein Framework gebunden sein, das eine kostenpflichtige Mitgliedschaft
|
||||
/// und eine Entitlement voraussetzt. Fällt WeatherKit einmal weg, wird nur die
|
||||
/// Abbildung ausgetauscht.
|
||||
public enum WeatherCondition: String, Equatable, Sendable, CaseIterable {
|
||||
public enum WeatherCondition: String, Equatable, Sendable, CaseIterable, Codable {
|
||||
case clear
|
||||
case mostlyClear
|
||||
case partlyCloudy
|
||||
@@ -36,7 +36,7 @@ public enum WeatherPlace: Equatable, Sendable, Codable {
|
||||
public var isCurrent: Bool { self == .current }
|
||||
}
|
||||
|
||||
public struct HourlyPoint: Equatable, Sendable, Identifiable {
|
||||
public struct HourlyPoint: Equatable, Sendable, Identifiable, Codable {
|
||||
public let date: Date
|
||||
public let temperature: Measurement<UnitTemperature>
|
||||
public let condition: WeatherCondition
|
||||
@@ -58,7 +58,7 @@ public struct HourlyPoint: Equatable, Sendable, Identifiable {
|
||||
/// Das ist keine Kür: die Nennung samt Link auf die Rechtshinweise ist
|
||||
/// Bedingung der Nutzung. Deshalb steht sie im Datenmodell und nicht in einer
|
||||
/// Notiz, die man beim Bauen der Oberfläche übersieht.
|
||||
public struct WeatherAttribution: Equatable, Sendable {
|
||||
public struct WeatherAttribution: Equatable, Sendable, Codable {
|
||||
public let name: String
|
||||
public let legalPageURL: URL
|
||||
public let logoURL: URL?
|
||||
@@ -70,7 +70,7 @@ public struct WeatherAttribution: Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
public struct WeatherSnapshot: Equatable, Sendable {
|
||||
public struct WeatherSnapshot: Equatable, Sendable, Codable {
|
||||
public let placeName: String
|
||||
public let temperature: Measurement<UnitTemperature>
|
||||
public let apparentTemperature: Measurement<UnitTemperature>
|
||||
|
||||
@@ -29,6 +29,11 @@ public final class WeatherModel {
|
||||
public init(source: WeatherKitSource = WeatherKitSource(), place: WeatherPlace = .current) {
|
||||
self.source = source
|
||||
self.place = place
|
||||
// Sofort zeigen, was zuletzt bekannt war. Ein Wert von vor einer Stunde
|
||||
// mit Zeitstempel ist eine Auskunft; ein Rädchen ist keine.
|
||||
if let known = cache.lastKnown(for: place) {
|
||||
state = .ready(known)
|
||||
}
|
||||
syncAuthorization()
|
||||
source.onLocationAuthorizationChange = { [weak self] in
|
||||
guard let self else { return }
|
||||
@@ -78,11 +83,16 @@ public final class WeatherModel {
|
||||
switch result {
|
||||
case .ready(let snapshot):
|
||||
cache.store(snapshot, for: place)
|
||||
try? cache.save()
|
||||
state = .ready(snapshot)
|
||||
case .unavailable(_, let reason):
|
||||
// Der letzte bekannte Stand bleibt sichtbar. Ein alter Messwert
|
||||
// mit Zeitstempel ist ehrlicher und nützlicher als ein leeres Feld.
|
||||
state = .unavailable(lastKnown: cache.lastKnown(for: place), reason: reason)
|
||||
case .loading, .idle:
|
||||
// Kommt von der Quelle nie zurück; hier stehen zu bleiben wäre
|
||||
// genau das Rädchen, das behoben werden sollte.
|
||||
state = cache.lastKnown(for: place).map { .ready($0) } ?? result
|
||||
default:
|
||||
state = result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user