← All repositories

reportage

A life-logging app for iPhone

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


commit f3f440a05dc6f794e4655787cd5065dc2fb322cd
parent 4acb98c53559c4ff3a8cfed9758517fab4a97eaf
Author: Michael Camilleri <[email protected]>
Date:   Sat, 17 Oct 2026 14:10:13 +0900

Capture the weather with each report

Reports recorded where they were made but not the weather there, so
the weather sections of the timeline and the detail view only ever
filled in for reports imported from Reporter.

This commit asks WeatherKit for the current conditions as soon as a
report has a location fix. The request runs alongside the address
lookup and within the same allowance, so the capture keeps its time
budget, and a slow or failed request leaves the weather empty rather
than holding up the report. The condition, temperatures, humidity,
pressure, wind, visibility, UV index and cloud cover are stored in
metric with Apple Weather as their source, and failures are logged so
a missing entitlement or service can be diagnosed.

The app now carries the WeatherKit entitlement, and the detail view
shows the Apple Weather mark and a link to its data sources beneath
the Weather section of reports with WeatherKit weather. Backfilling
historical weather stays with the derived context phase.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Diffstat

MNotes/Design.md | 16+++++++++++++---
MReportage.xcodeproj/project.pbxproj | 8++++++++
AReportage/Reportage.entitlements | 8++++++++
MReportage/Views/Report/ReportDetailView.swift | 43+++++++++++++++++++++++++++++++++++++++++++
MReportage/Views/Report/ReportDetails.swift | 23++++++++++++++---------
AShared/Capture/AppleWeather.swift | 42++++++++++++++++++++++++++++++++++++++++++
MShared/Capture/ContextCapture.swift | 32+++++++++++++++++++++++++++-----
Mproject.yml | 1+

8 files changed, 156 insertions(+), 17 deletions(-)

diff --git a/Notes/Design.md b/Notes/Design.md

@@ -641,8 +641,16 @@ re-geocoding the archive would have to run slowly in the background.
 
 ### Weather
 
-WeatherKit current conditions at the report's coordinate. This needs the
-WeatherKit capability and Apple Weather attribution in the UI. WeatherKit's
+WeatherKit current conditions at the report's coordinate, captured live
+(`AppleWeather`). The request starts as soon as there's a fix and runs
+alongside the address lookup, within the same allowance, so the capture keeps
+its budget; no answer in time leaves `weather` empty. The condition is stored
+as WeatherKit's description in the app's language, and the readings in metric.
+This needs the WeatherKit entitlement, and the App ID needs WeatherKit
+enabled. The report detail view shows the Apple Weather mark and a link to its
+data sources beneath the Weather section of reports with WeatherKit weather.
+
+WeatherKit's
 historical hourly data goes back to August 2021, so the April 2023 to present
 gap in the Reporter archive can be backfilled (about 5,000 requests, well
 within the free quota). Backfilled values are tagged `source: weatherKit` and
@@ -836,7 +844,9 @@ default); when included, each is the original JSON text as a string.
 5. **Quick logging.** `LogPassiveReportIntent` and the iOS surfaces it drives:
    the Control Center control, Lock Screen widget, Action button, Siri and
    Shortcuts. The Watch app is deferred.
-6. **Derived context.** Health, WeatherKit, photos, and backfilling them.
+6. **Derived context.** Health, photos, and backfilling them and historical
+   weather. Live weather was brought forward and is captured with each
+   report.
 7. **Visualisations.**
 
 ## Open Questions

diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj

@@ -67,6 +67,7 @@
 		E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */; };
 		E64BB44903A15E99126E73E5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */; };
 		E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */; };
+		E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC2D996880DB9C269F0203D5 /* AppleWeather.swift */; };
 		E8CC84072697836F87D8A00D /* TestHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */; };
 		EA730F4FD060F5843CC5B422 /* SurveyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7998F9826B899741323C0C7 /* SurveyView.swift */; };
 		EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = A49FBFD55992A79B9A6492C4 /* ReportageModel.xcdatamodeld */; };
@@ -148,6 +149,7 @@
 		BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduleTests.swift; sourceTree = "<group>"; };
 		BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailsTests.swift; sourceTree = "<group>"; };
 		BF998798373C9CCAD65999B3 /* TokenAnswer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenAnswer.swift; sourceTree = "<group>"; };
+		C17F34F71E3E13AF890DA2F3 /* Reportage.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Reportage.entitlements; sourceTree = "<group>"; };
 		C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetails.swift; sourceTree = "<group>"; };
 		C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
 		CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchive.swift; sourceTree = "<group>"; };
@@ -157,6 +159,7 @@
 		DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSettings.swift; sourceTree = "<group>"; };
 		E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
 		E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
+		EC2D996880DB9C269F0203D5 /* AppleWeather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleWeather.swift; sourceTree = "<group>"; };
 		F498961A14F24AE6CC37453C /* ReportDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailView.swift; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
@@ -216,6 +219,7 @@
 			children = (
 				633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */,
 				0B35602A218BE4EE399835FD /* Info.plist */,
+				C17F34F71E3E13AF890DA2F3 /* Reportage.entitlements */,
 				383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */,
 				60B58F5030E4A690025C51F5 /* Services */,
 				CA92EB21187B147C08A112F7 /* Views */,
@@ -239,6 +243,7 @@
 		507C6AD120A3E0F91316F4B6 /* Capture */ = {
 			isa = PBXGroup;
 			children = (
+				EC2D996880DB9C269F0203D5 /* AppleWeather.swift */,
 				9F3237323A968FA629020DA9 /* ContextCapture.swift */,
 				46FB42E5DB43201A13D6D141 /* PassiveLog.swift */,
 			);
@@ -527,6 +532,7 @@
 			files = (
 				81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */,
 				B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
+				E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
 				DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
 				D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
 				BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
@@ -764,6 +770,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CODE_SIGN_ENTITLEMENTS = Reportage/Reportage.entitlements;
 				CODE_SIGN_IDENTITY = "iPhone Developer";
 				CODE_SIGN_STYLE = Automatic;
 				INFOPLIST_FILE = Reportage/Info.plist;
@@ -782,6 +789,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CODE_SIGN_ENTITLEMENTS = Reportage/Reportage.entitlements;
 				CODE_SIGN_IDENTITY = "iPhone Developer";
 				CODE_SIGN_STYLE = Automatic;
 				INFOPLIST_FILE = Reportage/Info.plist;

diff --git a/Reportage/Reportage.entitlements b/Reportage/Reportage.entitlements

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>com.apple.developer.weatherkit</key>
+	<true/>
+</dict>
+</plist>

diff --git a/Reportage/Views/Report/ReportDetailView.swift b/Reportage/Views/Report/ReportDetailView.swift

@@ -1,6 +1,7 @@
 import CoreData
 import MapKit
 import SwiftUI
+import WeatherKit
 
 /// Where the timeline goes when a report is tapped.
 struct ReportRoute: Hashable {
@@ -127,6 +128,9 @@ struct ReportDetailPage: View {
                         ValueRow(row: row)
                     }
                 }
+                if section.kind == .weather, report.context.weather?.source == .weatherKit {
+                    AppleWeatherAttribution()
+                }
             }
             Button("Delete Report", role: .destructive, action: onDelete)
                 .font(.body.weight(.semibold))
@@ -233,6 +237,45 @@ extension LocationContext {
     }
 }
 
+/// The Apple Weather mark and a link to its data sources, which Apple asks
+/// for wherever WeatherKit's data is shown.
+private struct AppleWeatherAttribution: View {
+    @Environment(\.colorScheme) private var colorScheme
+    @State private var attribution: Loaded?
+
+    struct Loaded: Equatable {
+        var lightMark: URL
+        var darkMark: URL
+        var legalPage: URL
+    }
+
+    var body: some View {
+        HStack(spacing: Theme.itemGap) {
+            if let attribution {
+                AsyncImage(url: colorScheme == .dark ? attribution.darkMark : attribution.lightMark) { image in
+                    image.resizable().scaledToFit()
+                } placeholder: {
+                    Text(verbatim: "Apple Weather")
+                }
+                .frame(height: 12)
+                .accessibilityLabel(Text(verbatim: "Apple Weather"))
+                Link("Other Data Sources", destination: attribution.legalPage)
+                    .font(.footnote)
+                    .tint(Theme.muted)
+            }
+        }
+        .frame(minHeight: 20)
+        .task {
+            guard attribution == nil,
+                let loaded = try? await WeatherService.shared.attribution
+            else { return }
+            attribution = Loaded(
+                lightMark: loaded.combinedMarkLightURL, darkMark: loaded.combinedMarkDarkURL,
+                legalPage: loaded.legalPageURL)
+        }
+    }
+}
+
 /// A heading in small spaced capitals over rows divided by hairlines.
 private struct DetailSection<Content: View>: View {
     let title: String

diff --git a/Reportage/Views/Report/ReportDetails.swift b/Reportage/Views/Report/ReportDetails.swift

@@ -24,6 +24,11 @@ struct ReportDetails: Equatable {
     }
 
     struct Section: Equatable {
+        enum Kind: Equatable {
+            case time, place, location, weather, device, motion, sound, photos, record
+        }
+
+        var kind: Kind
         var title: String
         var rows: [Row]
     }
@@ -77,7 +82,7 @@ struct ReportDetails: Equatable {
         } else if let completedAt = report.completedAt {
             rows.append(row("Answered", f.dateTime(completedAt)))
         }
-        return Section(title: String(localized: "Time"), rows: rows.compactMap { $0 })
+        return Section(kind: .time, title: String(localized: "Time"), rows: rows.compactMap { $0 })
     }
 
     private static func place(_ placemark: Placemark, others: [Placemark], _ f: Formatter) -> Section {
@@ -108,7 +113,7 @@ struct ReportDetails: Equatable {
                 }
             rows.append(Row(label: label, value: address(other) ?? other.displayLocality ?? "").nonEmpty)
         }
-        return Section(title: String(localized: "Place"), rows: rows.compactMap { $0 })
+        return Section(kind: .place, title: String(localized: "Place"), rows: rows.compactMap { $0 })
     }
 
     private static func location(_ location: LocationContext, _ f: Formatter) -> Section {
@@ -124,7 +129,7 @@ struct ReportDetails: Equatable {
             row("Course", location.course.flatMap { $0 >= 0 ? f.bearing($0) : nil }),
             row("Fix Taken", location.timestamp.map(f.dateTime)),
         ]
-        return Section(title: String(localized: "Location"), rows: rows.compactMap { $0 })
+        return Section(kind: .location, title: String(localized: "Location"), rows: rows.compactMap { $0 })
     }
 
     private static func weather(_ weather: WeatherContext, _ f: Formatter) -> Section {
@@ -157,7 +162,7 @@ struct ReportDetails: Equatable {
             row("Rain Today", weather.precipitationToday.map(f.rainfall)),
             row("Source", source),
         ]
-        return Section(title: String(localized: "Weather"), rows: rows.compactMap { $0 })
+        return Section(kind: .weather, title: String(localized: "Weather"), rows: rows.compactMap { $0 })
     }
 
     private static func device(_ device: DeviceContext, _ f: Formatter) -> Section {
@@ -180,7 +185,7 @@ struct ReportDetails: Equatable {
             row("Battery State", state),
             row("Connection", connection),
         ]
-        return Section(title: String(localized: "Device"), rows: rows.compactMap { $0 })
+        return Section(kind: .device, title: String(localized: "Device"), rows: rows.compactMap { $0 })
     }
 
     private static func motion(_ motion: MotionContext, _ f: Formatter) -> Section {
@@ -191,7 +196,7 @@ struct ReportDetails: Equatable {
             row("Air Pressure", motion.pressure.map { f.pressure($0 * 10) }),
             row("Relative Altitude", motion.relativeAltitude.flatMap { f.metres($0, allowingNegative: true) }),
         ]
-        return Section(title: String(localized: "Motion"), rows: rows.compactMap { $0 })
+        return Section(kind: .motion, title: String(localized: "Motion"), rows: rows.compactMap { $0 })
     }
 
     private static func audio(_ audio: AudioContext, _ f: Formatter) -> Section {
@@ -205,7 +210,7 @@ struct ReportDetails: Equatable {
             row("Peak Level", audio.peak.map(f.decibels)),
             row("Source", source),
         ]
-        return Section(title: String(localized: "Sound"), rows: rows.compactMap { $0 })
+        return Section(kind: .sound, title: String(localized: "Sound"), rows: rows.compactMap { $0 })
     }
 
     private static func photos(_ photos: PhotosContext, _ f: Formatter) -> Section {
@@ -221,7 +226,7 @@ struct ReportDetails: Equatable {
             let label = photo.date.map(f.time) ?? String(localized: "Photo \(index + 1)")
             rows.append(Row(label: label, value: parts.joined(separator: " · ")).nonEmpty)
         }
-        return Section(title: String(localized: "Photos"), rows: rows.compactMap { $0 })
+        return Section(kind: .photos, title: String(localized: "Photos"), rows: rows.compactMap { $0 })
     }
 
     private static func record(_ report: Report, _ f: Formatter) -> Section {
@@ -230,7 +235,7 @@ struct ReportDetails: Equatable {
             row("Reporter Original", report.legacy == nil ? nil : String(localized: "Kept", comment: "The original Reporter data is stored")),
             row("ID", report.id.uuidString),
         ]
-        return Section(title: String(localized: "Record"), rows: rows.compactMap { $0 })
+        return Section(kind: .record, title: String(localized: "Record"), rows: rows.compactMap { $0 })
     }
 
     // MARK: Helpers

diff --git a/Shared/Capture/AppleWeather.swift b/Shared/Capture/AppleWeather.swift

@@ -0,0 +1,42 @@
+import CoreLocation
+import Foundation
+import OSLog
+import WeatherKit
+
+/// Current conditions from WeatherKit, for a report's live context.
+enum AppleWeather {
+    private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Weather")
+
+    /// The weather at `location` now, or `nil` if WeatherKit can't say.
+    /// Failures are logged: a missing entitlement or a service not yet
+    /// enabled for the App ID shows up here.
+    static func current(at location: CLLocation) async -> WeatherContext? {
+        do {
+            let current = try await WeatherService.shared.weather(for: location, including: .current)
+            return WeatherContext(current)
+        } catch {
+            logger.error("Couldn't get the weather: \(error)")
+            return nil
+        }
+    }
+}
+
+extension WeatherContext {
+    /// Current conditions in the context's units: °C, hectopascals, km/h,
+    /// kilometres and fractions.
+    init(_ current: CurrentWeather) {
+        self.init(source: .weatherKit)
+        condition = current.condition.description
+        temperature = current.temperature.converted(to: .celsius).value
+        feelsLike = current.apparentTemperature.converted(to: .celsius).value
+        dewPoint = current.dewPoint.converted(to: .celsius).value
+        humidity = current.humidity
+        pressure = current.pressure.converted(to: .hectopascals).value
+        windSpeed = current.wind.speed.converted(to: .kilometersPerHour).value
+        windGust = current.wind.gust?.converted(to: .kilometersPerHour).value
+        windDirection = current.wind.direction.converted(to: .degrees).value
+        visibility = current.visibility.converted(to: .kilometers).value
+        uvIndex = Double(current.uvIndex.value)
+        cloudCover = current.cloudCover
+    }
+}

diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift

@@ -7,8 +7,8 @@ import Network
     import UIKit
 #endif
 
-/// Captures the live context of a report: location and its address, and
-/// device state.
+/// Captures the live context of a report: location and its address, the
+/// weather there, and device state.
 ///
 /// Every provider runs at once and on its own, within the time budget. One
 /// that fails, is denied or runs out of time leaves its section `nil`; none
@@ -18,8 +18,11 @@ struct ContextCapture: Sendable {
     var budget: Duration = .seconds(10)
     /// A fix at least this accurate, in metres, ends the search early.
     var goodAccuracy: CLLocationAccuracy = 50
-    /// Time kept back from the location search for looking up the address.
+    /// Time kept back from the location search for looking up the address
+    /// and the weather, which both start once there's a fix.
     var geocodingAllowance: Duration = .seconds(3)
+    /// The current weather at a fix. Replaced in tests.
+    var weather: @Sendable (CLLocation) async -> WeatherContext? = { await AppleWeather.current(at: $0) }
 
     /// Captures the context. `onLocation` is called as soon as there's a
     /// fix, before its address has been looked up, so places near it can be
@@ -27,14 +30,32 @@ struct ContextCapture: Sendable {
     func capture(
         onLocation: @escaping @Sendable (LocationContext) -> Void = { _ in }
     ) async -> Context {
-        async let location = captureLocation(onLocation: onLocation)
+        // The weather needs the fix, so the location capture hands it over
+        // as soon as it has one, and the two lookups run side by side.
+        let (fixes, handOver) = AsyncStream.makeStream(of: CLLocation.self)
+        async let location = captureLocation(onFix: { handOver.yield($0) }, onLocation: onLocation)
+        async let weather = captureWeather(from: fixes)
         async let device = captureDevice()
-        return Context(location: await location, device: await device)
+        let captured = await location
+        handOver.finish()
+        return Context(location: captured, weather: await weather, device: await device)
+    }
+
+    // MARK: Weather
+
+    /// The weather at the first fix handed over, within the same allowance
+    /// as the address. `nil` if there's no fix, or no answer in time.
+    private func captureWeather(from fixes: AsyncStream<CLLocation>) async -> WeatherContext? {
+        for await fix in fixes {
+            return await withTimeout(geocodingAllowance) { await weather(fix) }
+        }
+        return nil
     }
 
     // MARK: Location
 
     private func captureLocation(
+        onFix: @Sendable (CLLocation) -> Void,
         onLocation: @Sendable (LocationContext) -> Void
     ) async -> LocationContext? {
         // Holding a session is what asks for authorisation. While the prompt
@@ -44,6 +65,7 @@ struct ContextCapture: Sendable {
         guard await Self.isAuthorised(session) else { return nil }
         guard let fix = await bestFix(within: budget - geocodingAllowance) else { return nil }
         var context = LocationContext(fix)
+        onFix(fix)
         onLocation(context)
         let placemarks = await withTimeout(geocodingAllowance) {
             await Self.placemarks(for: fix)

diff --git a/project.yml b/project.yml

@@ -47,6 +47,7 @@ targets:
       base:
         PRODUCT_BUNDLE_IDENTIFIER: net.inqk.reportage
         INFOPLIST_FILE: Reportage/Info.plist
+        CODE_SIGN_ENTITLEMENTS: Reportage/Reportage.entitlements
         TARGETED_DEVICE_FAMILY: "1"
         CODE_SIGN_STYLE: Automatic
       configs: