commit 634a4db3ce0e8aa15e0c426c7b27d40182ff9274
parent 6d5697de2b9791c61056b0400e69a9089655086e
Author: Michael Camilleri <[email protected]>
Date: Wed, 21 Oct 2026 09:03:15 +0900
Update older report addresses to MapKit's form
Reports imported from Reporter carry addresses from the geocoder of
their day, in whatever language the device used at the time, and without
the country code or the city with its region that MapKit gives new
reports. This commit adds 'Update Addresses' to the Data section of
Settings, which looks each address up again and replaces the old one.
Reporter's original stays in the legacy field. Imported Foursquare
venues are left as they are rather than matched to MapKit places.
Reports within 25 m of each other share a lookup. The update waits out
MapKit's throttling and keeps the screen on while it runs. MapKit's
addresses record their language and older ones don't, so the update
skips reports already in MapKit's form, and stopping and starting again
carries on where it left off. A spot with no address keeps the one it
had. The same update also covers reports filed before their address was
found.
The design notes now record that the Reporter import stays, that
missed prompts aren't recorded, and that multi-select can come later
without changing how choice answers are stored.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 29 | +++++++++++++++++++++-------- |
| M | Reportage.xcodeproj/project.pbxproj | | | 8 | ++++++++ |
| M | Reportage/AppDelegate.swift | | | 1 | + |
| M | Reportage/ReportageApp.swift | | | 1 | + |
| A | Reportage/Services/Places/AddressFill.swift | | | 266 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/DataSection.swift | | | 52 | ++++++++++++++++++++++++++++++++++++++++++++++++---- |
| M | Shared/Capture/ContextCapture.swift | | | 22 | ++++++++++++++-------- |
| A | Tests/Unit/AddressFillTests.swift | | | 83 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
8 files changed, 442 insertions(+), 20 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -920,6 +920,22 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
- **Place answers record the report's location** as where they were given,
as new answers do. Reporter stored the place's own location with each
answer; that becomes the place token's coordinate, and stays in `legacy`.
+- **Venues stay Foursquare's.** Imported venues keep their Foursquare IDs,
+ names and coordinates, and aren't matched to MapKit places: some have
+ closed, and a wrong match would be worse than none.
+- **Addresses are updated to MapKit's form afterwards.** Reporter's
+ addresses came from the geocoder of their day, in whatever language the
+ device used, without the country code or city with its region that
+ MapKit gives. **Update Addresses** in Settings' Data section looks each
+ one up again as capture does, in the user's first language and the
+ place's own, and replaces it; the original stays in `legacy`. Reports
+ within 25 m of each other share a lookup, since a fix is rarely better
+ than that: the archive's 20,552 located reports need about 1,700. It
+ waits out MapKit's throttling, keeps the screen on while it runs, and
+ skips reports whose address is already MapKit's (it records its
+ language), so stopping and starting again carries on. A spot MapKit has
+ no address for keeps the old one. It also covers new reports filed
+ before their address was found.
- **`legacy` is byte-exact.** The importer slices each snapshot's bytes out of
the export instead of re-serialising the decoded value, which would reorder
keys and reformat numbers.
@@ -1023,9 +1039,11 @@ the locale uses for weather. Sleep isn't charted.
of day is deferred.
See [Charts](#charts).
7. **Synced schema.** Settle the [open questions](#open-questions) that change
- synced data before the record formats are fixed: missed prompts, keeping
- past prompt settings, adding, removing and rewording
- questions, multi-select answers, and whether the Reporter import stays.
+ synced data before the record formats are fixed. The Reporter import
+ stays, with addresses updated to MapKit's form. Missed prompts aren't
+ recorded: a prompt that's never answered leaves nothing behind, as in
+ Reporter. Choice answers are already stored as lists, so multi-select
+ can come later without changing the format.
8. **Sync.** `CKSyncEngine`, both zones, first upload. Sync comes last
because CloudKit's Production schema can only be added to, so it should
be deployed once, after everything else has settled the shape of the
@@ -1035,11 +1053,6 @@ the locale uses for weather. Sleep isn't charted.
## Open Questions
-- **Missed prompts.** Should prompts that were delivered but never answered be
- recorded? Doing so costs little and makes the sampling honest for later
- analysis. Reporter didn't record them. The plan is deterministic, so the
- prompts sent on a day can be worked out again from the settings in force
- that day, if those are kept.
- **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/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -78,6 +78,7 @@
ACB648C0A1D54054E21C730E /* QuestionChartView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */; };
B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
+ B4669F1DB73592E4770A91FC /* AddressFillTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 056384B5C80E683A6A9440C0 /* AddressFillTests.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
B5642835F1FD86CA4AE39408 /* ContextSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0950575E9B01E6885B1BDA09 /* ContextSummary.swift */; };
BD1AA0F75635BF9C68DFA12A /* NarrativeRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = E67FAC24A684AA62ED63441A /* NarrativeRule.swift */; };
@@ -90,6 +91,7 @@
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */; };
D1FFB84FFDF0F659D8D78AEB /* ReportageWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EDD39E85D86AFF45B5672F3 /* ReportageWidgets.swift */; };
+ D3710CE243BC4BB46C12B8FE /* AddressFill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F0E3407B3FF5616EE56428B /* AddressFill.swift */; };
D3C3046B927DB98443E005C8 /* PlaceDirectory.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBBE80E95676BAEB53CE80E0 /* PlaceDirectory.swift */; };
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */; };
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F3237323A968FA629020DA9 /* ContextCapture.swift */; };
@@ -144,6 +146,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ 056384B5C80E683A6A9440C0 /* AddressFillTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddressFillTests.swift; sourceTree = "<group>"; };
0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummaryTests.swift; sourceTree = "<group>"; };
0950575E9B01E6885B1BDA09 /* ContextSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextSummary.swift; sourceTree = "<group>"; };
0A246867F8FAC9D3FFABD61D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -167,6 +170,7 @@
3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnswerSummaryTests.swift; sourceTree = "<group>"; };
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealExportVerificationTests.swift; sourceTree = "<group>"; };
3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportVerifier.swift; sourceTree = "<group>"; };
+ 3F0E3407B3FF5616EE56428B /* AddressFill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddressFill.swift; sourceTree = "<group>"; };
46FB42E5DB43201A13D6D141 /* PassiveLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassiveLog.swift; sourceTree = "<group>"; };
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchiveTests.swift; sourceTree = "<group>"; };
48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionEditorTests.swift; sourceTree = "<group>"; };
@@ -389,6 +393,7 @@
580063E6A7AE05D5C6C16830 /* Places */ = {
isa = PBXGroup;
children = (
+ 3F0E3407B3FF5616EE56428B /* AddressFill.swift */,
BBBE80E95676BAEB53CE80E0 /* PlaceDirectory.swift */,
76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */,
);
@@ -444,6 +449,7 @@
78F7B34F781A8894EDCB8C74 /* Unit */ = {
isa = PBXGroup;
children = (
+ 056384B5C80E683A6A9440C0 /* AddressFillTests.swift */,
3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */,
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */,
@@ -723,6 +729,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ B4669F1DB73592E4770A91FC /* AddressFillTests.swift in Sources */,
696B8F7586F680B1F5C41382 /* AnswerSummaryTests.swift in Sources */,
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */,
@@ -753,6 +760,7 @@
buildActionMask = 2147483647;
files = (
9F26886E122721BB3F2AFE7F /* AboutView.swift in Sources */,
+ D3710CE243BC4BB46C12B8FE /* AddressFill.swift in Sources */,
E3C74ABCE348FFF05890690E /* AnswerSummary.swift in Sources */,
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
diff --git a/Reportage/AppDelegate.swift b/Reportage/AppDelegate.swift
@@ -9,6 +9,7 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
let persistence = PersistenceController()
let inbox = PromptInbox()
lazy var healthFiller = HealthFiller(store: ReportStore(persistence: persistence))
+ lazy var addressUpdater = AddressUpdater(store: ReportStore(persistence: persistence))
/// Made with the delegate, as early in launch as there is.
let backgroundLocation = BackgroundLocation()
diff --git a/Reportage/ReportageApp.swift b/Reportage/ReportageApp.swift
@@ -15,6 +15,7 @@ struct ReportageApp: App {
.environment(\.reportStore, ReportStore(persistence: appDelegate.persistence))
.environment(appDelegate.inbox)
.environment(appDelegate.healthFiller)
+ .environment(appDelegate.addressUpdater)
.tint(Theme.accent)
.task { await prepareQuestions() }
}
diff --git a/Reportage/Services/Places/AddressFill.swift b/Reportage/Services/Places/AddressFill.swift
@@ -0,0 +1,266 @@
+import CoreData
+import CoreLocation
+import Foundation
+import MapKit
+import UIKit
+
+/// A report with a location whose address isn't in the form MapKit gives
+/// new reports: one imported from Reporter, whose address came from the
+/// geocoder of its day, or one captured before its address was found.
+struct AddressTarget: Equatable, Sendable {
+ var id: UUID
+ var coordinate: Coordinate
+}
+
+/// Reports close enough together to share one address lookup.
+struct AddressSpot: Equatable, Sendable {
+ /// Where the address is looked up: the first report's location.
+ var coordinate: Coordinate
+ var reportIDs: [UUID]
+}
+
+enum AddressSpots {
+ /// Groups `targets` so each is within `radius` metres of its spot's
+ /// coordinate, the spots with the most reports first. A fix is rarely
+ /// better than a few tens of metres, so reports this close are as likely
+ /// to have been at one address as at two.
+ static func group(_ targets: [AddressTarget], within radius: Double = 25) -> [AddressSpot] {
+ let cell = radius / metresPerDegree
+ var spots: [AddressSpot] = []
+ /// Spot indices by grid cell, so a target is compared only with the
+ /// spots in the cells around it.
+ var grid: [Cell: [Int]] = [:]
+ for target in targets {
+ let home = Cell(target.coordinate, size: cell)
+ let near = home.neighbours.lazy.flatMap { grid[$0] ?? [] }.first { index in
+ distance(spots[index].coordinate, target.coordinate) <= radius
+ }
+ if let near {
+ spots[near].reportIDs.append(target.id)
+ } else {
+ grid[home, default: []].append(spots.count)
+ spots.append(AddressSpot(coordinate: target.coordinate, reportIDs: [target.id]))
+ }
+ }
+ // Stable, so spots with as many reports keep the targets' order.
+ return spots.enumerated()
+ .sorted { lhs, rhs in
+ lhs.element.reportIDs.count != rhs.element.reportIDs.count
+ ? lhs.element.reportIDs.count > rhs.element.reportIDs.count : lhs.offset < rhs.offset
+ }
+ .map(\.element)
+ }
+
+ private static let metresPerDegree = 111_320.0
+
+ /// Metres between two nearby coordinates, treating the earth as flat
+ /// over the distance.
+ static func distance(_ a: Coordinate, _ b: Coordinate) -> Double {
+ let latitude = (a.latitude - b.latitude) * metresPerDegree
+ let longitude =
+ (a.longitude - b.longitude) * metresPerDegree * cos((a.latitude + b.latitude) / 2 * .pi / 180)
+ return (latitude * latitude + longitude * longitude).squareRoot()
+ }
+
+ /// A square of the grid, `size` degrees of latitude high and as many
+ /// metres wide at its latitude.
+ private struct Cell: Hashable {
+ var row: Int
+ var column: Int
+
+ init(row: Int, column: Int) {
+ self.row = row
+ self.column = column
+ }
+
+ init(_ coordinate: Coordinate, size: Double) {
+ row = Int((coordinate.latitude / size).rounded(.down))
+ let width = size / max(cos(coordinate.latitude * .pi / 180), 0.01)
+ column = Int((coordinate.longitude / width).rounded(.down))
+ }
+
+ var neighbours: [Cell] {
+ (-1...1).flatMap { dr in (-1...1).map { dc in Cell(row: row + dr, column: column + dc) } }
+ }
+ }
+}
+
+/// Looks up the address at a coordinate.
+protocol AddressLooking: Sendable {
+ /// The address in the user's first language, then in the place's own
+ /// language if it differs, or none if there's no address there. Throws
+ /// `AddressLookupError.throttled` when asked too often.
+ func placemarks(at coordinate: Coordinate) async throws -> [Placemark]
+}
+
+enum AddressLookupError: Error {
+ case throttled
+}
+
+/// Addresses from MapKit, as new reports are given them.
+struct MapKitAddressLookup: AddressLooking {
+ func placemarks(at coordinate: Coordinate) async throws -> [Placemark] {
+ do {
+ return try await ContextCapture.placemarks(
+ for: CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude))
+ } catch let error as MKError where error.code == .loadingThrottled {
+ throw AddressLookupError.throttled
+ }
+ }
+}
+
+/// How far an address update has got.
+struct AddressFillProgress: Equatable, Sendable {
+ /// How many reports needed an address when the update started.
+ var total = 0
+ var updated = 0
+ /// Reports at spots MapKit has no address for. They keep the one they had.
+ var unfound = 0
+ /// Whether the update is waiting out MapKit's throttling.
+ var isWaiting = false
+}
+
+/// Gives reports the address MapKit would give them today, replacing one
+/// in an older form. Reports already in MapKit's form are left alone, so an
+/// update that stops can be run again to carry on.
+struct AddressFill: Sendable {
+ let store: ReportStore
+ let lookup: any AddressLooking
+ var radius = 25.0
+ /// How long to wait after MapKit throttles a lookup before trying again.
+ var throttlePause: Duration = .seconds(60)
+
+ /// Returns how far it got. `progress` is told after each spot. An error
+ /// other than throttling ends the update; addresses saved before it are
+ /// kept.
+ @discardableResult
+ func fill(progress: (@Sendable (AddressFillProgress) async -> Void)? = nil) async throws
+ -> AddressFillProgress
+ {
+ let targets = try await store.addressTargets()
+ var state = AddressFillProgress(total: targets.count)
+ await progress?(state)
+ for spot in AddressSpots.group(targets, within: radius) {
+ try Task.checkCancellation()
+ var placemarks: [Placemark]?
+ while placemarks == nil {
+ do {
+ placemarks = try await lookup.placemarks(at: spot.coordinate)
+ } catch AddressLookupError.throttled {
+ state.isWaiting = true
+ await progress?(state)
+ try await Task.sleep(for: throttlePause)
+ state.isWaiting = false
+ }
+ }
+ if let placemarks, !placemarks.isEmpty {
+ try await store.setPlacemarks(placemarks, for: spot.reportIDs)
+ state.updated += spot.reportIDs.count
+ } else {
+ state.unfound += spot.reportIDs.count
+ }
+ await progress?(state)
+ }
+ return state
+ }
+}
+
+extension ReportStore {
+ /// Reports with a location whose address isn't in MapKit's form, newest
+ /// first. MapKit's addresses record their language; older ones don't.
+ func addressTargets() async throws -> [AddressTarget] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "context != nil")
+ request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
+ request.fetchBatchSize = 500
+ var targets: [AddressTarget] = []
+ for entity in try context.fetch(request) {
+ guard let id = entity.id, let data = entity.context,
+ let location = try ModelCoding.decode(Context.self, from: data).location,
+ location.placemark?.language == nil
+ else { continue }
+ targets.append(AddressTarget(id: id, coordinate: location.coordinate))
+ // Decoded contexts aren't needed once read.
+ context.refresh(entity, mergeChanges: false)
+ }
+ return targets
+ }
+ }
+
+ /// Gives the reports `placemarks` as their address: the first in the
+ /// user's first language, and the rest in other languages. The address
+ /// they had is replaced; for an imported report, Reporter's stays in
+ /// `legacy`.
+ func setPlacemarks(_ placemarks: [Placemark], for ids: [UUID], now: Date = Date()) async throws {
+ guard let first = placemarks.first else { return }
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", ids)
+ for entity in try context.fetch(request) {
+ guard let data = entity.context else { continue }
+ var captured = try ModelCoding.decode(Context.self, from: data)
+ guard captured.location != nil else { continue }
+ captured.location?.placemark = first
+ captured.location?.localisedPlacemarks = placemarks.count > 1 ? Array(placemarks.dropFirst()) : nil
+ entity.context = try ModelCoding.encode(captured)
+ entity.modifiedAt = now
+ }
+ try context.save()
+ }
+ }
+}
+
+/// Runs an address update for the app when the user asks, keeping the
+/// screen on meanwhile: a locked iPhone would suspend the app, and the
+/// update with it.
+@MainActor
+@Observable
+final class AddressUpdater {
+ /// How far the update has got, while it runs.
+ private(set) var progress: AddressFillProgress?
+ /// How the last update ended, until another starts.
+ private(set) var outcome: AddressFillProgress?
+
+ @ObservationIgnored private let store: ReportStore
+ @ObservationIgnored private var task: Task<Void, Never>?
+ private static let log = EventLog.shared.category("Addresses")
+
+ init(store: ReportStore) {
+ self.store = store
+ }
+
+ var isUpdating: Bool { progress != nil }
+
+ func start() {
+ guard task == nil else { return }
+ progress = AddressFillProgress()
+ outcome = nil
+ UIApplication.shared.isIdleTimerDisabled = true
+ task = Task {
+ defer {
+ outcome = progress
+ outcome?.isWaiting = false
+ task = nil
+ progress = nil
+ UIApplication.shared.isIdleTimerDisabled = false
+ }
+ do {
+ let last = try await AddressFill(store: store, lookup: MapKitAddressLookup()).fill { state in
+ await MainActor.run { self.progress = state }
+ }
+ Self.log.info("Updated \(last.updated) addresses; \(last.unfound) had none")
+ } catch is CancellationError {
+ Self.log.info("Stopped updating addresses after \(self.progress?.updated ?? 0)")
+ } catch {
+ Self.log.error("Couldn't update addresses: \(error)")
+ }
+ }
+ }
+
+ func stop() {
+ task?.cancel()
+ }
+}
diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift
@@ -3,11 +3,12 @@ import OSLog
import SwiftUI
import UniformTypeIdentifiers
-/// Importing a Reporter export, exporting the store as JSON, and filling in
-/// Health data for earlier reports.
+/// Importing a Reporter export, exporting the store as JSON, filling in
+/// Health data for earlier reports, and updating older addresses.
struct DataSection: View {
@Environment(\.reportStore) private var store
@Environment(HealthFiller.self) private var healthFiller: HealthFiller?
+ @Environment(AddressUpdater.self) private var addressUpdater: AddressUpdater?
@State private var task: DataTask?
@State private var isChoosingImport = false
@State private var exported: ExportFile?
@@ -35,7 +36,7 @@ struct DataSection: View {
} label: {
TaskLabel("Import from Reporter", isRunning: task == .importing)
}
- .disabled(task != nil || store == nil)
+ .disabled(task != nil || store == nil || addressUpdater?.isUpdating == true)
.settingsRow()
Button {
Task { await export() }
@@ -64,12 +65,30 @@ struct DataSection: View {
}
}
}
+ if let addressUpdater {
+ Button {
+ if addressUpdater.isUpdating {
+ addressUpdater.stop()
+ } else {
+ addressUpdater.start()
+ }
+ } label: {
+ TaskLabel(
+ addressUpdater.isUpdating ? "Stop Updating Addresses" : "Update Addresses",
+ isRunning: addressUpdater.isUpdating)
+ }
+ .disabled(task == .importing || task == .deleting || store == nil)
+ .settingsRow()
+ SettingsNote { AddressNote(updater: addressUpdater) }
+ }
Button(role: .destructive) {
isConfirmingDelete = true
} label: {
TaskLabel("Delete All Data", isRunning: task == .deleting)
}
- .disabled(task != nil || store == nil || healthFiller?.isFillingPast == true)
+ .disabled(
+ task != nil || store == nil || healthFiller?.isFillingPast == true
+ || addressUpdater?.isUpdating == true)
.settingsRow()
} header: {
SettingsHeading("Data")
@@ -226,6 +245,31 @@ struct DataSection: View {
}
}
+/// What updating addresses does, how far it has got, or how it ended.
+private struct AddressNote: View {
+ let updater: AddressUpdater
+
+ var body: some View {
+ if let progress = updater.progress {
+ if progress.isWaiting {
+ Text("Updated \(progress.updated) of \(progress.total) reports. Waiting for Apple Maps, which limits how often addresses can be looked up…")
+ } else {
+ Text("Updated \(progress.updated) of \(progress.total) reports. Keep Reportage open until it finishes; the screen stays on meanwhile.")
+ }
+ } else if let outcome = updater.outcome {
+ if outcome.updated + outcome.unfound < outcome.total {
+ Text("Updated \(outcome.updated) of \(outcome.total) reports before stopping. Update again to carry on.")
+ } else if outcome.unfound > 0 {
+ Text("Updated ^[\(outcome.updated) report](inflect: true). Apple Maps had no address for ^[\(outcome.unfound) report](inflect: true), which kept the one it had.")
+ } else {
+ Text("Updated ^[\(outcome.updated) report](inflect: true).")
+ }
+ } else {
+ Text("Gives reports imported from Reporter, or filed before their address was found, the address Apple Maps gives new reports.")
+ }
+ }
+}
+
/// A button's title, with a spinner while its task runs.
private struct TaskLabel: View {
let title: LocalizedStringKey
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -103,7 +103,7 @@ struct ContextCapture: Sendable {
onFix(fix)
onLocation(context)
let placemarks = await withTimeout(geocodingAllowance) {
- await Self.placemarks(for: fix)
+ try? await Self.placemarks(for: fix)
}
context.placemark = placemarks?.first
if let others = placemarks?.dropFirst(), !others.isEmpty {
@@ -258,23 +258,29 @@ struct ContextCapture: Sendable {
/// The fix's address in the user's first language and, where the
/// place's own language differs, in that language too. Together they let
/// an address be shown in the local language when the user knows it,
- /// and in their first language otherwise, as place names are.
- private static func placemarks(for location: CLLocation) async -> [Placemark] {
+ /// and in their first language otherwise, as place names are. A
+ /// location MapKit has no address for has none; other errors, such as
+ /// MapKit's throttling, are thrown.
+ static func placemarks(for location: CLLocation) async throws -> [Placemark] {
guard let first = preferredLanguages(limit: 1).first,
- let placemark = await placemark(for: location, language: first)
+ let placemark = try await placemark(for: location, language: first)
else { return [] }
guard let local = placemark.countryCode.flatMap(localLanguage(ofRegion:)),
Locale.Language(identifier: local).languageCode != Locale.Language(identifier: first).languageCode,
- let localPlacemark = await self.placemark(for: location, language: local)
+ let localPlacemark = try await self.placemark(for: location, language: local)
else { return [placemark] }
return [placemark, localPlacemark]
}
- private static func placemark(for location: CLLocation, language: String) async -> Placemark? {
+ private static func placemark(for location: CLLocation, language: String) async throws -> Placemark? {
guard let request = MKReverseGeocodingRequest(location: location) else { return nil }
request.preferredLocale = Locale(identifier: language)
- guard let item = try? await request.mapItems.first else { return nil }
- return Placemark(item, language: language)
+ do {
+ guard let item = try await request.mapItems.first else { return nil }
+ return Placemark(item, language: language)
+ } catch let error as MKError where error.code == .placemarkNotFound {
+ return nil
+ }
}
/// The main language of a region, such as `ja` for `JP`. Chinese keeps
diff --git a/Tests/Unit/AddressFillTests.swift b/Tests/Unit/AddressFillTests.swift
@@ -0,0 +1,83 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("AddressFill")
+struct AddressFillTests {
+ /// Gives each coordinate an address naming its latitude, throttling the
+ /// first lookup and finding nothing south of the equator.
+ private actor FakeLookup: AddressLooking {
+ private(set) var lookups: [Coordinate] = []
+ private var hasThrottled = false
+
+ func placemarks(at coordinate: Coordinate) async throws -> [Placemark] {
+ if !hasThrottled {
+ hasThrottled = true
+ throw AddressLookupError.throttled
+ }
+ lookups.append(coordinate)
+ guard coordinate.latitude > 0 else { return [] }
+ return [
+ Placemark(name: "\(coordinate.latitude)", language: "en", cityWithContext: "City"),
+ Placemark(name: "\(coordinate.latitude)", language: "ja", cityWithContext: "市"),
+ ]
+ }
+ }
+
+ private static func report(latitude: Double, placemark: Placemark?) -> Report {
+ var context = Context()
+ context.location = LocationContext(
+ coordinate: Coordinate(latitude: latitude, longitude: 139.7), placemark: placemark)
+ return Report(
+ id: UUID(), date: Date(timeIntervalSince1970: 0), timeZone: "Asia/Tokyo", kind: .manual,
+ trigger: .app, state: .complete, context: context, modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ @Test("Reports within the radius share a spot, the spots with most reports first")
+ func spots() {
+ func target(_ metresNorth: Double) -> AddressTarget {
+ AddressTarget(id: UUID(), coordinate: Coordinate(latitude: 35 + metresNorth / 111_320, longitude: 139.7))
+ }
+ let targets = [target(0), target(500), target(10), target(20), target(510), target(30)]
+ let spots = AddressSpots.group(targets, within: 25)
+ #expect(spots.map(\.reportIDs) == [
+ [targets[0].id, targets[2].id, targets[3].id],
+ [targets[1].id, targets[4].id],
+ [targets[5].id],
+ ])
+ #expect(abs(AddressSpots.distance(targets[0].coordinate, targets[1].coordinate) - 500) < 0.01)
+ }
+
+ @Test("Older addresses are replaced with MapKit's, and reports already in MapKit's form are left alone")
+ func fill() async throws {
+ let store = ReportStore(persistence: makeTestPersistence())
+ let imported = Self.report(latitude: 35, placemark: Placemark(name: "Old", locality: "杉並区"))
+ let missing = Self.report(latitude: 35.0001, placemark: nil)
+ let current = Self.report(latitude: 36, placemark: Placemark(name: "New", language: "en"))
+ let nowhere = Self.report(latitude: -10, placemark: Placemark(name: "Sea"))
+ for report in [imported, missing, current, nowhere] {
+ try await store.insert(report)
+ }
+
+ let lookup = FakeLookup()
+ let fill = AddressFill(store: store, lookup: lookup, throttlePause: .zero)
+ let progress = try await fill.fill()
+ #expect(progress == AddressFillProgress(total: 3, updated: 2, unfound: 1))
+ // Two reports 11 m apart share a lookup, retried once after throttling.
+ #expect(await lookup.lookups.count == 2)
+
+ let updated = try #require(try await store.report(id: missing.id))
+ #expect(updated.context.location?.placemark?.cityWithContext == "City")
+ #expect(updated.context.location?.localisedPlacemarks?.map(\.language) == ["ja"])
+ #expect(updated.modifiedAt > imported.modifiedAt)
+ let replaced = try #require(try await store.report(id: imported.id))
+ #expect(replaced.context.location?.placemark == updated.context.location?.placemark)
+ #expect(try await store.report(id: current.id)?.context == current.context)
+ #expect(try await store.report(id: nowhere.id)?.context == nowhere.context)
+
+ // Run again, only the report without an address is looked up.
+ let again = try await fill.fill()
+ #expect(again == AddressFillProgress(total: 1, updated: 0, unfound: 1))
+ }
+}