commit 820b3a8769490d9a70f999c865cd83a41da66316
parent bbedf891669f64ae6bfe528bc1afa2fbf2490974
Author: Michael Camilleri <[email protected]>
Date: Fri, 16 Oct 2026 20:52:09 +0900
Capture location and device state with each report
Reports made in Reportage saved an empty context, so new entries had no
line saying where they were made and place answers had no coordinate.
This commit captures live context from the moment a survey opens: the
first location fix within 50 metres, or the best one within the budget,
with its address looked up in the device's first two languages, plus
battery and connectivity. The first survey asks for 'While Using'
access, and the budget starts only once the user has answered, so a fix
is not lost while the prompt is on screen. Place answers now record
where they were given, and entries show the city with its region.
Placemarks gain the fields Apple Maps now provides — the language, the
region code, the city with its region and the full and short addresses —
alongside Reporter's, along with a list of the same address in the
user's other languages. All are optional, so older exports still read.
'Always' access is left for Phase 3, when Log for Later will need it;
the usage description and the upgrade request are ready.
Narratives also become more reliable. The model returns text unchanged
about three times in ten, which stored the draft as finished, so an
unchanged or failing result is now tried again, up to three attempts.
Each narrative records the version of the polishing pass that wrote it,
so changing the pass rewrites every entry the next time it is shown.
While an entry is being rewritten, its text is hidden in place and
'Writing narrative…' shows over it, so the row keeps its height.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
15 files changed, 513 insertions(+), 44 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -162,6 +162,7 @@ rules from `DisplayRule.builtIn`, keyed by ID.
| `modifiedAt` | Used for last-writer-wins on sync. |
| `narrative` | Local only. The polished entry (see [Entries](#entries)). Derived, so not exported or synced: each device writes its own. |
| `narrativeDraft` | Local only. The draft `narrative` was made from. The narrative is current only while it matches the report's draft. |
+| `narrativeVersion` | Local only. The version of the polishing pass that wrote `narrative`. An older version is rewritten. |
### Response
@@ -349,9 +350,18 @@ with these instructions:
change), a capital is only removed from an ordinary word, a place lowercased
after 'at' gains an article unless it reads without one ('home', 'work'),
and no article appears before a placeholder that didn't have one.
-- **Outcomes.** A passing output is stored. A failing one stores the draft, so
- the report isn't retried every time it's shown. If the model is unavailable,
- nothing is stored and it's tried again later.
+- **Attempts.** The model returns text unchanged about three times in ten
+ even when it fixes the same text on other runs ('at Home' left as it was),
+ so an unchanged or failing output is tried again, up to three attempts. The
+ first passing output that changes something is used.
+- **Outcomes.** A passing output is stored. If every attempt fails or leaves
+ the draft unchanged, the draft is stored, so the report isn't retried every
+ time it's shown. If the model is unavailable, nothing is stored and it's
+ tried again later.
+- **Versions.** Each narrative stores the version of the polishing pass that
+ wrote it (`NarrativePolisher.version`). Raising the version, when the
+ instructions or the check change, rewrites every entry the next time it's
+ shown.
- One request runs at a time, responses are capped at 150 tokens (one input
once made the model generate until its 8,192-token limit), and scrolling
away cancels a waiting request.
@@ -483,9 +493,25 @@ denied provider leaves its section `nil`. It never blocks saving the report.
### Location
`CLLocationUpdate.liveUpdates()`, taking the first fix within an accuracy
-threshold, then falling back to the best fix within the budget. Reverse
+threshold (50 m), then falling back to the best fix within the budget, less
+3 seconds kept for looking up the address. Holding a `CLServiceSession` asks
+for 'While Using' authorisation the first time a survey opens. Capture starts
+when the survey opens, so the fix describes the moment of the report, and a
+place answer records the fix as where it was given.
+
+'Always' is requested later, as an upgrade, when the user turns on prompts in
+Phase 3: Log for Later records location without opening the app, and asking
+before any feature needs it would leave the request unexplained (and invite
+App Review questions). `LocationAuthorization.requestAlways()` is ready for
+that.
+
+Addresses come from MapKit as `MKMapItem`s; the placemark keeps Reporter's
+fields where they still exist, plus the language, the region code, the city
+with its region and the full and short addresses. In a Simulator test the
+whole capture took 0.2 s. Reverse
geocoding uses MapKit's `MKReverseGeocodingRequest` (`CLGeocoder` is deprecated
-in iOS 26), once per language the user knows, using `preferredLocale`, so the
+in iOS 26), once per language the user knows (for now, the first two of the
+device's preferred languages), using `preferredLocale`, so the
placemark can be shown by the same rule as place names. Reporter's archive
mixes Japanese and English placemarks depending on the device language at the
time. Apple throttles geocoding, so two requests per report is fine but
@@ -532,6 +558,10 @@ In order of preference:
the rule is simple: **if headphones of any kind are connected, don't touch
the audio session.**
+Microphone sampling is deferred. It needs its own permission and the route
+check verified on a device, so ambient noise waits for Health in Phase 6, and
+microphone sampling is reconsidered then.
+
### Device and photos
Battery from `UIDevice`, connectivity from `NWPathMonitor`. Photos come from
@@ -689,8 +719,8 @@ default); when included, each is the original JSON text as a string.
analysis. Reporter didn't record them.
- **Defaults.** Default number of prompts per day and the minimum gap. The
archive averages about 3.4 notification-triggered reports per day.
-- **"Always" location.** Is "Always" location acceptable, given it's the price
- of location on background passive logs?
+- **"Always" location.** Settled: requested as an upgrade when prompts are
+ turned on (see [Location](#location)).
- **Backfills.** Weather from August 2021 onwards and Health from 2014 onwards.
Both are optional and can be done at any time. Location answers skipped
since Reporter lost venue lookup (2026-09-01) could be filled in from each
diff --git a/Notes/ExportFormat.md b/Notes/ExportFormat.md
@@ -124,9 +124,13 @@ metric. - `location`: `coordinate`; `altitude` (m); `horizontalAccuracy` and `verticalAccuracy` (m); `speed` (m/s); `course` (degrees from true north); - `timestamp` (date of the fix); `placemark` with `name`, `subThoroughfare`, - `thoroughfare`, `subLocality`, `locality`, `subAdministrativeArea`, - `administrativeArea`, `postalCode`, `country`, `inlandWater` and `ocean`. + `timestamp` (date of the fix); `placemark`, the address in the user's first + language; and `localisedPlacemarks`, the same address in the user's other + languages. A placemark has `name`, `subThoroughfare`, `thoroughfare`, + `subLocality`, `locality`, `subAdministrativeArea`, `administrativeArea`, + `postalCode`, `country`, `inlandWater` and `ocean` (the fields Reporter + recorded), and `language` (BCP 47), `countryCode` (ISO 3166-1), + `cityWithContext`, `fullAddress` and `shortAddress` (from Apple Maps). - `weather`: `source` (`wunderground`, `darkSky` or `weatherKit`); `backfilled` (true when fetched after the fact); `condition`; `temperature`, `feelsLike` and `dewPoint` (°C); `humidity` (0–1); `pressure` (hPa);
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -41,8 +41,10 @@
C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */; };
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 878CE0FF7A2598F4197E8E61 /* Environment.swift */; };
C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
+ CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */; };
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */; };
+ D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F3237323A968FA629020DA9 /* ContextCapture.swift */; };
D7F95FB1236974113EBE93FA /* ReportKind+Title.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5591E042089D038B59B26E9F /* ReportKind+Title.swift */; };
D9A8839569734F5CEAC43A44 /* TokenAnswer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF998798373C9CCAD65999B3 /* TokenAnswer.swift */; };
DF632654B427EE32C44C6F78 /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F200EBD30BC12D2313E6C6F /* Context.swift */; };
@@ -101,8 +103,10 @@
8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DisplayRule.swift; sourceTree = "<group>"; };
917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporterTests.swift; sourceTree = "<group>"; };
94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultQuestions.swift; sourceTree = "<group>"; };
+ 9F3237323A968FA629020DA9 /* ContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCapture.swift; sourceTree = "<group>"; };
A00E589A8387E7A1E348503C /* InlineCasing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InlineCasing.swift; sourceTree = "<group>"; };
A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
+ A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCaptureTests.swift; sourceTree = "<group>"; };
A3BE62142CCC4A791F05163A /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = "<group>"; };
AF426915E941538164D91B18 /* NarrativePolisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NarrativePolisher.swift; sourceTree = "<group>"; };
B007E6BACAA214C7332EF77C /* Question.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Question.swift; sourceTree = "<group>"; };
@@ -171,6 +175,14 @@
path = Models;
sourceTree = "<group>";
};
+ 507C6AD120A3E0F91316F4B6 /* Capture */ = {
+ isa = PBXGroup;
+ children = (
+ 9F3237323A968FA629020DA9 /* ContextCapture.swift */,
+ );
+ path = Capture;
+ sourceTree = "<group>";
+ };
5253526A8B292306AB33EFF0 /* Support */ = {
isa = PBXGroup;
children = (
@@ -194,6 +206,7 @@
6939F7C2C95274DF2BB62D20 /* Shared */ = {
isa = PBXGroup;
children = (
+ 507C6AD120A3E0F91316F4B6 /* Capture */,
4EF63181707B888F4ECDB980 /* Models */,
B9570B011A58C1B1BF00FB73 /* Persistence */,
);
@@ -203,6 +216,7 @@
78F7B34F781A8894EDCB8C74 /* Unit */ = {
isa = PBXGroup;
children = (
+ A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */,
5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */,
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
@@ -399,6 +413,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */,
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */,
4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
@@ -418,6 +433,7 @@
buildActionMask = 2147483647;
files = (
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
+ D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */,
406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */,
diff --git a/Reportage/Info.plist b/Reportage/Info.plist
@@ -24,6 +24,10 @@ <false/> <key>LSRequiresIPhoneOS</key> <true/> + <key>NSLocationAlwaysAndWhenInUseUsageDescription</key> + <string>With Always, Reportage can record where you are when you log a report from a notification without opening the app.</string> + <key>NSLocationWhenInUseUsageDescription</key> + <string>Reportage records where you are with each report, and suggests places nearby when you say where you are.</string> <key>UILaunchScreen</key> <dict/> <key>UISupportedInterfaceOrientations</key>
diff --git a/Reportage/Services/Narrative/NarrativePolisher.swift b/Reportage/Services/Narrative/NarrativePolisher.swift
@@ -26,6 +26,15 @@ actor NarrativePolisher {
static let instructions =
"Proofread the input. Correct spelling, grammar and punctuation only. Reply with the corrected text only."
+ /// The version of the polishing pass. Raise it when the instructions or
+ /// the check change, so stored narratives are written again.
+ static let version: Int16 = 2
+
+ /// Attempts per entry. The model leaves text unchanged about three times
+ /// in ten even when it would fix it on another run, so an unchanged or
+ /// failing result is tried again.
+ static let attempts = 3
+
private let model = SystemLanguageModel(guardrails: .permissiveContentTransformations)
/// One request at a time, so scrolling quickly doesn't queue up dozens of
@@ -43,21 +52,27 @@ actor NarrativePolisher {
defer { release() }
guard !Task.isCancelled else { return .unavailable }
- let output: String
- do {
- let session = LanguageModelSession(model: model, instructions: Self.instructions)
- output = try await session.respond(
- to: protected.text, options: GenerationOptions(maximumResponseTokens: 150)
- ).content.trimmingCharacters(in: .whitespacesAndNewlines)
- } catch {
- return .unavailable
- }
-
- let problem = await MainActor.run {
- NarrativeCheck.problem(in: output, comparedWith: protected)
+ var passedUnchanged = false
+ for _ in 1...Self.attempts {
+ guard !Task.isCancelled else { return .unavailable }
+ let output: String
+ do {
+ let session = LanguageModelSession(model: model, instructions: Self.instructions)
+ output = try await session.respond(
+ to: protected.text, options: GenerationOptions(maximumResponseTokens: 150)
+ ).content.trimmingCharacters(in: .whitespacesAndNewlines)
+ } catch {
+ return .unavailable
+ }
+ let problem = await MainActor.run {
+ NarrativeCheck.problem(in: output, comparedWith: protected)
+ }
+ guard problem == nil else { continue }
+ if output != protected.text { return .polished(protected.restore(output)) }
+ passedUnchanged = true
}
- guard problem == nil else { return .rejected }
- return .polished(protected.restore(output))
+ // Every attempt left the draft as it was, or failed the check.
+ return passedUnchanged ? .polished(draft.text) : .rejected
}
private func acquire() async {
diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift
@@ -210,12 +210,10 @@ struct ReportRow: View {
)
ReportSummaryText(
entry: entry(for: summary.draft),
+ isWriting: isWriting,
details: summary.details,
context: summary.context
)
- if isWriting {
- WritingIndicator()
- }
}
}
.task(id: describer.isLoaded ? summary.draft?.text : nil) {
@@ -223,8 +221,9 @@ struct ReportRow: View {
}
}
- /// The polished entry if it was made from the current draft, otherwise
- /// the draft itself.
+ /// The stored narrative if it was made from the current draft, otherwise
+ /// the draft itself. A narrative from an older polishing pass is still
+ /// shown until it's rewritten.
private func entry(for draft: EntryDraft?) -> String? {
guard let draft else { return nil }
if report.narrativeDraft == draft.text, let narrative = report.narrative {
@@ -233,15 +232,18 @@ struct ReportRow: View {
return draft.text
}
+ private func isCurrent(_ draft: EntryDraft) -> Bool {
+ report.narrativeDraft == draft.text && report.narrativeVersion == NarrativePolisher.version
+ }
+
/// Polishes the entry the first time it's shown, and again whenever its
/// draft changes. A rejected polish stores the draft, so it isn't retried
/// every time the row appears; an unavailable model stores nothing.
private func polish(_ draft: EntryDraft?) async {
- guard describer.isLoaded, let draft, report.narrativeDraft != draft.text,
- let store, let id = report.id
+ guard describer.isLoaded, let draft, !isCurrent(draft), let store, let id = report.id
else { return }
- isWriting = true
- defer { isWriting = false }
+ withAnimation { isWriting = true }
+ defer { withAnimation { isWriting = false } }
let narrative: String
switch await NarrativePolisher.shared.polish(draft) {
case .polished(let text): narrative = text
@@ -309,7 +311,7 @@ struct ReportKindLabel: View {
}
}
-/// Shown under a draft while its narrative is being written.
+/// Shown in place of an entry while its narrative is being written.
struct WritingIndicator: View {
var body: some View {
HStack(spacing: 6) {
@@ -317,7 +319,7 @@ struct WritingIndicator: View {
.controlSize(.mini)
Text("Writing narrative…", comment: "Shown while an entry is being polished")
}
- .font(.footnote.italic())
+ .font(Theme.serif(.body).italic())
.foregroundStyle(Theme.muted)
.transition(.opacity)
}
@@ -325,6 +327,9 @@ struct WritingIndicator: View {
struct ReportSummaryText: View {
let entry: String?
+ /// Whether the entry is being rewritten. It's hidden but keeps its space,
+ /// so the row doesn't change height, with a message over it.
+ let isWriting: Bool
let details: [AnswerDetail]
let context: String?
@@ -337,6 +342,13 @@ struct ReportSummaryText: View {
Text(entry)
.font(Theme.serif(.body))
.foregroundStyle(Theme.ink)
+ .opacity(isWriting ? 0 : 1)
+ .accessibilityHidden(isWriting)
+ .overlay(alignment: .topLeading) {
+ if isWriting {
+ WritingIndicator()
+ }
+ }
} else if details.isEmpty {
Text("No answers", comment: "Shown for a report whose questions were all skipped")
.font(Theme.serif(.body).italic())
diff --git a/Reportage/Views/Home/ReportSummary.swift b/Reportage/Views/Home/ReportSummary.swift
@@ -24,11 +24,14 @@ struct ReportSummary: Equatable {
self.context = Self.contextLine(context)
}
- /// The locality and weather, for example 'Kichijōji · 18° Cloudy'.
+ /// Where and the weather, for example 'Suginami, Tokyo · 18° Cloudy'.
+ /// Imported placemarks have no city with its region, so they show the
+ /// most specific locality they have.
static func contextLine(_ context: Context) -> String? {
var parts: [String] = []
if let placemark = context.location?.placemark,
- let locality = placemark.subLocality ?? placemark.locality ?? placemark.name
+ let locality = placemark.cityWithContext ?? placemark.subLocality ?? placemark.locality
+ ?? placemark.name
{
parts.append(locality)
}
@@ -81,9 +84,10 @@ extension ReportStore {
}
extension ReportStore {
- /// Stores the polished entry for a report, with the draft it came from.
- /// The entry stays valid until the report's draft changes, for example
- /// when an answer is edited or a token renamed.
+ /// Stores the polished entry for a report, with the draft it came from
+ /// and the version of the polishing pass. The entry stays valid until the
+ /// report's draft changes, for example when an answer is edited or a
+ /// token renamed, or the polishing pass changes.
func saveNarrative(_ narrative: String, draft: String, for reportID: UUID) async throws {
let context = persistence.newBackgroundContext()
try await context.perform {
@@ -93,6 +97,7 @@ extension ReportStore {
guard let entity = try context.fetch(request).first else { return }
entity.narrative = narrative
entity.narrativeDraft = draft
+ entity.narrativeVersion = NarrativePolisher.version
try context.save()
}
}
diff --git a/Reportage/Views/Survey/SurveyModel.swift b/Reportage/Views/Survey/SurveyModel.swift
@@ -19,6 +19,8 @@ final class SurveyModel {
/// Whether the last page change went forwards, for the page transition.
private(set) var isMovingForward = true
private var answers: [String: ResponseValue] = [:]
+ /// Live context, captured from when the survey opens.
+ private var contextTask: Task<Context, Never>?
init(
kind: ReportKind,
@@ -139,14 +141,40 @@ final class SurveyModel {
pickers[question.id]?.clear()
}
+ // MARK: Context
+
+ /// Starts capturing the report's live context. Called when the survey
+ /// opens, so the context describes the moment the report is about.
+ func startCapture(_ capture: ContextCapture = ContextCapture()) {
+ guard contextTask == nil else { return }
+ contextTask = Task { await capture.capture() }
+ }
+
+ /// The captured context, waiting for the capture if it's still running.
+ /// It finishes within its budget of the survey opening.
+ func capturedContext() async -> Context {
+ await contextTask?.value ?? Context()
+ }
+
// MARK: Saving
/// The finished report, with a response for every question in the
/// survey (skipped questions have no value), and the tokens created
/// while answering that the report uses.
- func makeReport(id: UUID = UUID(), now: Date) -> (report: Report, newTokens: [Token]) {
+ func makeReport(
+ id: UUID = UUID(),
+ now: Date,
+ context: Context = Context()
+ ) -> (report: Report, newTokens: [Token]) {
let responses = questions.map { question in
- Response(questionID: question.id, prompt: question.prompt, value: value(for: question))
+ var value = value(for: question)
+ // A place answer records where it was given.
+ if case .place(var answer) = value, let location = context.location {
+ answer.coordinate = location.coordinate
+ answer.accuracy = location.horizontalAccuracy
+ value = .place(answer)
+ }
+ return Response(questionID: question.id, prompt: question.prompt, value: value)
}
let newTokens = questions.flatMap { question in
pickers[question.id]?.usedNewTokens(now: now) ?? []
@@ -159,6 +187,7 @@ final class SurveyModel {
trigger: .app,
state: .complete,
completedAt: now,
+ context: context,
responses: responses,
modifiedAt: now
)
diff --git a/Reportage/Views/Survey/SurveyView.swift b/Reportage/Views/Survey/SurveyView.swift
@@ -42,12 +42,14 @@ struct SurveySheet: View {
[QuestionKind.tokens, .people, .location].contains($0.kind)
}
let vocabulary = try await store.vocabulary(for: tokenQuestions.map(\.id))
- model = SurveyModel(
+ let model = SurveyModel(
kind: request.kind,
date: request.date,
questions: questions,
vocabulary: vocabulary
)
+ model.startCapture()
+ self.model = model
} catch {
loadError = error.localizedDescription
}
@@ -148,8 +150,9 @@ struct SurveyView: View {
private func save() {
guard let store, !isSaving else { return }
isSaving = true
- let (report, newTokens) = model.makeReport(now: Date())
Task {
+ let context = await model.capturedContext()
+ let (report, newTokens) = model.makeReport(now: Date(), context: context)
do {
try await store.insert(report, newTokens: newTokens)
dismiss()
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -0,0 +1,241 @@
+import CoreLocation
+import Foundation
+import MapKit
+import Network
+
+#if os(iOS)
+ import UIKit
+#endif
+
+/// Captures the live context of a report: location and its address, 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
+/// of them can stop the report being saved.
+struct ContextCapture: Sendable {
+ /// The whole capture's budget.
+ 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.
+ var geocodingAllowance: Duration = .seconds(3)
+
+ func capture() async -> Context {
+ async let location = captureLocation()
+ async let device = captureDevice()
+ return Context(location: await location, device: await device)
+ }
+
+ // MARK: Location
+
+ private func captureLocation() async -> LocationContext? {
+ // Holding a session is what asks for authorisation. While the prompt
+ // is on screen the budget hasn't started: the user is reading it.
+ let session = CLServiceSession(authorization: .whenInUse)
+ defer { session.invalidate() }
+ guard await Self.isAuthorised(session) else { return nil }
+ guard let fix = await bestFix(within: budget - geocodingAllowance) else { return nil }
+ var context = LocationContext(fix)
+ let placemarks = await withTimeout(geocodingAllowance) {
+ await Self.placemarks(for: fix)
+ }
+ context.placemark = placemarks?.first
+ if let others = placemarks?.dropFirst(), !others.isEmpty {
+ context.localisedPlacemarks = Array(others)
+ }
+ return context
+ }
+
+ /// Waits until the user has answered the authorisation prompt, if one is
+ /// showing, and reports whether location may be used. Gives up after a
+ /// minute so a prompt left on screen can't hold up saving forever.
+ private static func isAuthorised(_ session: CLServiceSession) async -> Bool {
+ switch CLLocationManager().authorizationStatus {
+ case .authorizedWhenInUse, .authorizedAlways: return true
+ case .denied, .restricted: return false
+ case .notDetermined: break
+ @unknown default: break
+ }
+ let answer = await withTimeout(.seconds(60)) { () async -> Bool? in
+ do {
+ for try await diagnostic in session.diagnostics {
+ if diagnostic.authorizationRequestInProgress { continue }
+ return !(diagnostic.authorizationDenied || diagnostic.authorizationDeniedGlobally
+ || diagnostic.authorizationRestricted)
+ }
+ } catch {}
+ return nil
+ }
+ return answer ?? false
+ }
+
+ /// The first fix within `goodAccuracy`, or the best one received within
+ /// `limit`.
+ private func bestFix(within limit: Duration) async -> CLLocation? {
+ await withTaskGroup(of: CLLocation??.self) { group in
+ group.addTask {
+ var best: CLLocation?
+ do {
+ for try await update in CLLocationUpdate.liveUpdates() {
+ if update.authorizationDenied || update.authorizationDeniedGlobally
+ || update.authorizationRestricted
+ {
+ break
+ }
+ if let location = update.location, location.horizontalAccuracy >= 0,
+ location.horizontalAccuracy < best?.horizontalAccuracy ?? .infinity
+ {
+ best = location
+ }
+ if let best, best.horizontalAccuracy <= goodAccuracy { break }
+ if Task.isCancelled { break }
+ }
+ } catch {}
+ return .some(best)
+ }
+ group.addTask {
+ try? await Task.sleep(for: limit)
+ return .none
+ }
+
+ // When time runs out, cancel the search and take its best fix.
+ var result: CLLocation?
+ while let next = await group.next() {
+ if case .some(let fix) = next {
+ result = fix
+ break
+ }
+ group.cancelAll()
+ }
+ group.cancelAll()
+ return result
+ }
+ }
+
+ /// The fix's address in each of the user's first two languages.
+ private static func placemarks(for location: CLLocation) async -> [Placemark] {
+ var placemarks: [Placemark] = []
+ for language in preferredLanguages(limit: 2) {
+ guard let request = MKReverseGeocodingRequest(location: location) else { break }
+ request.preferredLocale = Locale(identifier: language)
+ guard let item = try? await request.mapItems.first else { continue }
+ placemarks.append(Placemark(item, language: language))
+ }
+ return placemarks
+ }
+
+ /// Distinct language codes from the user's preferred languages, in order.
+ static func preferredLanguages(limit: Int) -> [String] {
+ var languages: [String] = []
+ for identifier in Locale.preferredLanguages {
+ guard let code = Locale(identifier: identifier).language.languageCode?.identifier,
+ !languages.contains(code)
+ else { continue }
+ languages.append(code)
+ if languages.count == limit { break }
+ }
+ return languages
+ }
+
+ // MARK: Device
+
+ private func captureDevice() async -> DeviceContext? {
+ var device = DeviceContext()
+ #if os(iOS)
+ (device.batteryLevel, device.batteryState) = await MainActor.run {
+ let current = UIDevice.current
+ current.isBatteryMonitoringEnabled = true
+ defer { current.isBatteryMonitoringEnabled = false }
+ let level = current.batteryLevel
+ let state: DeviceContext.BatteryState? =
+ switch current.batteryState {
+ case .unplugged: .unplugged
+ case .charging: .charging
+ case .full: .full
+ case .unknown: nil
+ @unknown default: nil
+ }
+ // The level is -1 when it's unknown, as in the Simulator.
+ return (level >= 0 ? Double(level) : nil, state)
+ }
+ #endif
+ device.connectivity = await withTimeout(.seconds(2)) { await Self.connectivity() }
+ return device == DeviceContext() ? nil : device
+ }
+
+ private static func connectivity() async -> DeviceContext.Connectivity {
+ let monitor = NWPathMonitor()
+ defer { monitor.cancel() }
+ for await path in monitor {
+ guard path.status == .satisfied else { return .none }
+ if path.usesInterfaceType(.wifi) || path.usesInterfaceType(.wiredEthernet) { return .wifi }
+ if path.usesInterfaceType(.cellular) { return .cellular }
+ return .wifi
+ }
+ return .none
+ }
+}
+
+/// Runs `operation`, giving up with `nil` after `timeout`.
+func withTimeout<T: Sendable>(
+ _ timeout: Duration,
+ 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: timeout)
+ return nil
+ }
+ let first = await group.next() ?? nil
+ group.cancelAll()
+ return first
+ }
+}
+
+extension LocationContext {
+ init(_ location: CLLocation) {
+ // Negative accuracies mean the reading is invalid, as in Core
+ // Location, and an invalid vertical accuracy invalidates the altitude.
+ let verticalValid = location.verticalAccuracy >= 0
+ self.init(
+ coordinate: Coordinate(
+ latitude: location.coordinate.latitude, longitude: location.coordinate.longitude),
+ altitude: verticalValid ? location.altitude : nil,
+ horizontalAccuracy: location.horizontalAccuracy >= 0 ? location.horizontalAccuracy : nil,
+ verticalAccuracy: verticalValid ? location.verticalAccuracy : nil,
+ speed: location.speed >= 0 ? location.speed : nil,
+ course: location.course >= 0 ? location.course : nil,
+ timestamp: location.timestamp
+ )
+ }
+}
+
+extension Placemark {
+ init(_ item: MKMapItem, language: String) {
+ let representations = item.addressRepresentations
+ self.init(
+ name: item.name,
+ locality: representations?.cityName,
+ country: representations?.regionName,
+ language: language,
+ countryCode: representations?.region?.identifier,
+ cityWithContext: representations?.cityWithContext,
+ fullAddress: item.address?.fullAddress,
+ shortAddress: item.address?.shortAddress
+ )
+ }
+}
+
+/// Location authorisation beyond 'While Using'.
+enum LocationAuthorization {
+ /// Asks to upgrade to 'Always'. iOS asks for this only after 'While
+ /// Using' has been granted. Phase 3 calls it when the user turns on
+ /// prompts, because Log for Later records location from a notification
+ /// without opening the app; asking before then would leave the request
+ /// unexplained.
+ static func requestAlways() -> CLServiceSession {
+ CLServiceSession(authorization: .always)
+ }
+}
diff --git a/Shared/Models/Context.swift b/Shared/Models/Context.swift
@@ -28,7 +28,11 @@ struct LocationContext: Codable, Hashable, Sendable {
var course: Double?
/// When the fix was taken.
var timestamp: Date?
+ /// The address in the user's first language.
var placemark: Placemark?
+ /// The address in the user's other languages, so it can be shown by the
+ /// same rule as place names. Reporter recorded one placemark only.
+ var localisedPlacemarks: [Placemark]?
}
struct Placemark: Codable, Hashable, Sendable {
@@ -43,6 +47,15 @@ struct Placemark: Codable, Hashable, Sendable {
var country: String?
var inlandWater: String?
var ocean: String?
+ /// The BCP 47 language the names are in. Unknown for imported reports,
+ /// whose placemarks are in whatever language the device used.
+ var language: String?
+ /// ISO 3166-1 region code, for example `JP`.
+ var countryCode: String?
+ /// The city with its region, as Apple Maps writes it.
+ var cityWithContext: String?
+ var fullAddress: String?
+ var shortAddress: String?
}
struct WeatherContext: Codable, Hashable, Sendable {
diff --git a/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents b/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents
@@ -26,6 +26,7 @@
<attribute name="modifiedAt" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="narrative" optional="YES" attributeType="String"/>
<attribute name="narrativeDraft" optional="YES" attributeType="String"/>
+ <attribute name="narrativeVersion" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="promptedAt" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="state" attributeType="String"/>
<attribute name="timeZone" attributeType="String"/>
diff --git a/Tests/Unit/ContextCaptureTests.swift b/Tests/Unit/ContextCaptureTests.swift
@@ -0,0 +1,90 @@
+import CoreLocation
+import Foundation
+import MapKit
+import Testing
+
+@testable import Reportage
+
+@Suite("ContextCapture")
+struct ContextCaptureTests {
+
+ @Test("A fix becomes location context, with invalid readings left out")
+ func locationContext() {
+ let location = CLLocation(
+ coordinate: CLLocationCoordinate2D(latitude: 35.703, longitude: 139.580),
+ altitude: 60, horizontalAccuracy: 8, verticalAccuracy: -1, course: -1, speed: 1.5,
+ timestamp: Date(timeIntervalSince1970: 100))
+ let context = LocationContext(location)
+ #expect(context.coordinate == Coordinate(latitude: 35.703, longitude: 139.580))
+ #expect(context.horizontalAccuracy == 8)
+ #expect(context.altitude == nil)
+ #expect(context.verticalAccuracy == nil)
+ #expect(context.course == nil)
+ #expect(context.speed == 1.5)
+ #expect(context.timestamp == Date(timeIntervalSince1970: 100))
+ }
+
+ @Test("A map item's address becomes a placemark in the language it was asked for")
+ func placemark() throws {
+ let address = try #require(MKAddress(fullAddress: "1-2-3 Kichijoji, Musashino, Tokyo", shortAddress: "Kichijoji"))
+ let item = MKMapItem(location: CLLocation(latitude: 35.7, longitude: 139.58), address: address)
+ item.name = "Kichijoji Station"
+ let placemark = Placemark(item, language: "en")
+ #expect(placemark.name == "Kichijoji Station")
+ #expect(placemark.language == "en")
+ #expect(placemark.fullAddress == "1-2-3 Kichijoji, Musashino, Tokyo")
+ #expect(placemark.shortAddress == "Kichijoji")
+ }
+
+ @Test("Older contexts without the new fields still decode")
+ func backwardCompatible() throws {
+ let json = #"{"location":{"coordinate":{"latitude":1,"longitude":2},"placemark":{"name":"Home"}}}"#
+ let context = try ModelCoding.decode(Context.self, from: Data(json.utf8))
+ #expect(context.location?.placemark?.name == "Home")
+ #expect(context.location?.localisedPlacemarks == nil)
+ }
+
+ @Test("Preferred languages are distinct codes, in order")
+ func languages() {
+ let languages = ContextCapture.preferredLanguages(limit: 2)
+ #expect(languages.count <= 2)
+ #expect(Set(languages).count == languages.count)
+ }
+
+ @Test("A timeout gives up with nil, and a quick result comes through")
+ func timeout() async {
+ let slow = await withTimeout(.milliseconds(50)) { () async -> Int? in
+ try? await Task.sleep(for: .seconds(5))
+ return 1
+ }
+ #expect(slow == nil)
+ let quick = await withTimeout(.seconds(5)) { () async -> Int? in 2 }
+ #expect(quick == 2)
+ }
+}
+
+@MainActor
+@Suite("SurveyModel context")
+struct SurveyModelContextTests {
+
+ @Test("The captured context is saved, and place answers record where they were given")
+ func placeCoordinate() {
+ let question = Question(
+ id: "place", prompt: "Where?", kind: .location, askOn: .random, order: 0,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ let model = SurveyModel(
+ kind: .manual, date: Date(), questions: [question],
+ vocabulary: ["place": [VocabularyEntry(id: "P1", text: "Home", useCount: 1)]])
+ model.pickers["place"]?.toggle("P1")
+
+ var context = Context()
+ context.location = LocationContext(
+ coordinate: Coordinate(latitude: 1.5, longitude: 2.5), horizontalAccuracy: 12)
+ let report = model.makeReport(now: Date(), context: context).report
+
+ #expect(report.context == context)
+ #expect(
+ report.responses.first?.value
+ == .place(PlaceAnswer(tokenID: "P1", coordinate: Coordinate(latitude: 1.5, longitude: 2.5), accuracy: 12)))
+ }
+}
diff --git a/Tests/Unit/ReportSummaryTests.swift b/Tests/Unit/ReportSummaryTests.swift
@@ -179,6 +179,10 @@ struct ReportSummaryTests {
context.location?.placemark?.subLocality = "Kichijōji"
#expect(ReportSummary.contextLine(context) == "Kichijōji")
+ context.location?.placemark?.cityWithContext = "Suginami, Tokyo"
+ #expect(ReportSummary.contextLine(context) == "Suginami, Tokyo")
+ context.location?.placemark?.cityWithContext = nil
+
context.weather = WeatherContext(source: .darkSky, condition: "Cloudy", temperature: 18.2)
let line = ReportSummary.contextLine(context)
#expect(line?.hasPrefix("Kichijōji · ") == true)
diff --git a/project.yml b/project.yml
@@ -34,6 +34,8 @@ targets:
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
ITSAppUsesNonExemptEncryption: false
LSRequiresIPhoneOS: true
+ NSLocationWhenInUseUsageDescription: Reportage records where you are with each report, and suggests places nearby when you say where you are.
+ NSLocationAlwaysAndWhenInUseUsageDescription: With Always, Reportage can record where you are when you log a report from a notification without opening the app.
UILaunchScreen: {}
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait