commit a344a0a1dbe879dfa9b76518cadb02adde15650c
parent 259001b0d79770345c214898428f18dfff514e36
Author: Michael Camilleri <[email protected]>
Date: Tue, 20 Oct 2026 15:20:37 +0900
Hold an 'Always' location session for background captures
An Instant Report filed from a notification sometimes saved without a
location. The capture ran for its whole budget and Core Location sent a
single update with no fix, flagged serviceSessionRequired. Since iOS 18,
'Always' only counts while the app holds an .always CLServiceSession,
and a new session only takes effect in the foreground. The capture took
its own session after the action had launched the app in the
background, so it granted nothing. Captures only succeeded when Core
Location happened to have a recent fix on hand.
This commit adds BackgroundLocation, which holds one .always session
for as long as the app runs while 'Always' is granted. It is made with
the app delegate, so the session is taken again within the few seconds
Core Location allows after any launch, and it is renewed each time the
app comes to the foreground, where a new session always takes effect.
It also monitors significant location changes, so Core Location
relaunches the app as the user moves, which keeps the session going and
leaves a recent fix for the next capture. iOS will remind the user from
time to time that Reportage has used their location in the background.
The session logs its diagnostics to the event log when they change, so
a session that is held back after a background launch shows up as
'insufficientlyInUse'. The capture's comment and the design notes, which
claimed the capture's own session was enough, are corrected.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 17 | +++++++++++++---- |
| M | Reportage.xcodeproj/project.pbxproj | | | 4 | ++++ |
| M | Reportage/AppDelegate.swift | | | 2 | ++ |
| M | Reportage/ReportageApp.swift | | | 1 | + |
| A | Reportage/Services/BackgroundLocation.swift | | | 116 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Shared/Capture/ContextCapture.swift | | | 8 | ++++---- |
6 files changed, 140 insertions(+), 8 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -533,10 +533,19 @@ Category `prompt`: when the prompt first fired. If a survey or Settings is already open, it waits until that closes. -Location for background actions requires 'Always' authorisation, and the -capture holds an 'Always' session when it's granted: a 'While Using' session -doesn't cover an app launched in the background, and Core Location withholds -its updates. Without 'Always', passive reports logged from a notification get +Location for background actions requires 'Always' authorisation, and +'Always' only counts while the app holds an `.always` `CLServiceSession`. A +new session only takes effect in the foreground: one started when an action +launches the app grants nothing, and Core Location withholds its updates. So +with 'Always' granted, the app holds one session for as long as it runs, +renewed each time it comes to the foreground and taken again as soon as it +launches, which Core Location allows for a few seconds after any launch if +the app held one when it last stopped. It also monitors significant location +changes, so Core Location relaunches it as the user moves, which keeps the +session going and leaves a recent fix for the next capture. iOS reminds the +user now and then that Reportage has used their location in the background, +which is true and fine. A force-quit or restart ends the session until the +app is next opened. Without 'Always', passive reports logged from a notification get no location, and the Prompts section of Settings says so, with a link to Settings.
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -44,6 +44,7 @@
7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */; };
7A6543B7C48EC93D468EBBD8 /* PlacePhrase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577EC17EF58F65207B7EA15D /* PlacePhrase.swift */; };
7ACDA81EC3D7811F891CA029 /* ReportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */; };
+ 811704907EE199CC627F0CE5 /* BackgroundLocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */; };
81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */; };
83E954F0DAC9719D2AA02111 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C7E4E96538BB14AD6956CA /* HomeView.swift */; };
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */; };
@@ -223,6 +224,7 @@
E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
E60426297403B9F8632343D8 /* SchemaMigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SchemaMigrationTests.swift; sourceTree = "<group>"; };
E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
+ EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackgroundLocation.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>"; };
F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsView.swift; sourceTree = "<group>"; };
@@ -358,6 +360,7 @@
isa = PBXGroup;
children = (
7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */,
+ EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */,
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */,
729C291798F29C69029E7DB7 /* InstantReportLogger.swift */,
AD85758A0521ED681067B90F /* Export */,
@@ -690,6 +693,7 @@
81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */,
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
+ 811704907EE199CC627F0CE5 /* BackgroundLocation.swift in Sources */,
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */,
diff --git a/Reportage/AppDelegate.swift b/Reportage/AppDelegate.swift
@@ -9,6 +9,8 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
let persistence = PersistenceController()
let inbox = PromptInbox()
lazy var healthFiller = HealthFiller(store: ReportStore(persistence: persistence))
+ /// Made with the delegate, as early in launch as there is.
+ let backgroundLocation = BackgroundLocation()
private let log = EventLog.shared.category("Prompts")
diff --git a/Reportage/ReportageApp.swift b/Reportage/ReportageApp.swift
@@ -22,6 +22,7 @@ struct ReportageApp: App {
switch phase {
case .active:
Task { await PromptScheduler().refresh() }
+ appDelegate.backgroundLocation.refresh(renewing: true)
// Health can only be read while the iPhone is unlocked.
appDelegate.healthFiller.fillRecent()
case .background:
diff --git a/Reportage/Services/BackgroundLocation.swift b/Reportage/Services/BackgroundLocation.swift
@@ -0,0 +1,116 @@
+import CoreLocation
+
+/// Keeps 'Always' location in effect, so a capture in the background, such
+/// as an Instant Report from a notification, gets a fix.
+///
+/// 'Always' only counts while the app holds an `.always` `CLServiceSession`,
+/// and a new one only takes effect if it's started in the foreground. One
+/// started when a notification action launches the app grants nothing, and
+/// Core Location holds the capture's updates back. So a session is held for
+/// as long as the app runs: started in the foreground, and taken again as
+/// soon as the app launches, which Core Location allows for a few seconds
+/// after any launch if the app held one when it last stopped.
+///
+/// Watching for significant location changes keeps that going: Core
+/// Location relaunches the app into the background as the user moves, the
+/// session is taken again each time, and there's a recent fix to start from.
+/// iOS reminds the user from time to time that the app has used their
+/// location in the background, which it has.
+@MainActor
+final class BackgroundLocation: NSObject, CLLocationManagerDelegate {
+ private let manager = CLLocationManager()
+ private var session: CLServiceSession?
+ private var watching: Task<Void, Never>?
+ /// The session's last state in the log, kept across renewals so a
+ /// renewal that changes nothing isn't logged.
+ private var loggedState: String?
+ private let log = EventLog.shared.category("Location")
+
+ /// Takes the session at once, if 'Always' is granted. Created before
+ /// launch finishes, both to take the session within Core Location's
+ /// grace period and to have a delegate for the location change that
+ /// launched the app.
+ override init() {
+ super.init()
+ manager.delegate = self
+ refresh()
+ }
+
+ /// Starts or stops holding the session and watching for changes to
+ /// match the authorisation. `renewing` replaces a held session, as
+ /// coming to the foreground should: a session started then always takes
+ /// effect, where one taken in the background may not have.
+ func refresh(renewing: Bool = false) {
+ guard manager.authorizationStatus == .authorizedAlways else {
+ stop()
+ return
+ }
+ if session == nil {
+ log.info("Holding a location session for 'Always'")
+ }
+ if session == nil || renewing {
+ hold()
+ }
+ manager.startMonitoringSignificantLocationChanges()
+ }
+
+ /// Takes a new session in place of any held, and logs whether it's in
+ /// effect: one that isn't says it's insufficiently in use until the app
+ /// comes to the foreground.
+ private func hold() {
+ let old = session
+ let session = CLServiceSession(authorization: .always)
+ self.session = session
+ old?.invalidate()
+ watching?.cancel()
+ watching = Task {
+ do {
+ for try await diagnostic in session.diagnostics {
+ note(Self.state(of: diagnostic))
+ }
+ } catch {}
+ }
+ }
+
+ private func stop() {
+ guard let session else { return }
+ watching?.cancel()
+ watching = nil
+ session.invalidate()
+ self.session = nil
+ loggedState = nil
+ manager.stopMonitoringSignificantLocationChanges()
+ log.info("Stopped holding a location session: no 'Always'")
+ }
+
+ private func note(_ state: String) {
+ guard state != loggedState else { return }
+ loggedState = state
+ log.info("Location session: \(state)")
+ }
+
+ private static func state(of diagnostic: CLServiceSession.Diagnostic) -> String {
+ let flags = [
+ ("insufficientlyInUse", diagnostic.insufficientlyInUse),
+ ("alwaysAuthorizationDenied", diagnostic.alwaysAuthorizationDenied),
+ ("authorizationDenied", diagnostic.authorizationDenied),
+ ("authorizationDeniedGlobally", diagnostic.authorizationDeniedGlobally),
+ ("authorizationRestricted", diagnostic.authorizationRestricted),
+ ("serviceSessionRequired", diagnostic.serviceSessionRequired),
+ ]
+ let set = flags.filter(\.1).map(\.0)
+ return set.isEmpty ? "in effect" : "held back, \(set.joined(separator: ", "))"
+ }
+
+ // The manager was made on the main thread, so it calls back there.
+
+ nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
+ MainActor.assumeIsolated { refresh() }
+ }
+
+ /// The fix itself isn't needed: Core Location keeps the latest for the
+ /// next capture.
+ nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}
+
+ nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {}
+}
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -86,10 +86,10 @@ struct ContextCapture: Sendable {
) 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.
- // With 'Always' granted, the session asks for it too: a 'While
- // Using' session doesn't cover a capture in the background, such as
- // an Instant Report from a notification, and Core Location holds
- // its updates back.
+ // With 'Always' granted, the session asks for it too, though in the
+ // background that only works while the app already holds one
+ // started earlier: Core Location won't let a new one take effect
+ // there. `BackgroundLocation` holds that one in the app.
let isAlways = CLLocationManager().authorizationStatus == .authorizedAlways
let session = CLServiceSession(authorization: isAlways ? .always : .whenInUse)
Self.log.info("Holding a location session for \(isAlways ? "'Always'" : "'While Using'")")