← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/BackgroundLocation.swift (4848B)

1import CoreLocation
2
3/// Keeps 'Always' location in effect, so a capture in the background, such
4/// as an Instant Report from a notification, gets a fix.
5///
6/// 'Always' only counts while the app holds an `.always` `CLServiceSession`,
7/// and a new one only takes effect if it's started in the foreground. One
8/// started when a notification action launches the app grants nothing, and
9/// Core Location holds the capture's updates back. So a session is held for
10/// as long as the app runs: started in the foreground, and taken again as
11/// soon as the app launches, which Core Location allows for a few seconds
12/// after any launch if the app held one when it last stopped.
13///
14/// Watching for significant location changes keeps that going: Core
15/// Location relaunches the app into the background as the user moves, the
16/// session is taken again each time, and there's a recent fix to start from.
17/// iOS reminds the user from time to time that the app has used their
18/// location in the background, which it has.
19@MainActor
20final class BackgroundLocation: NSObject, CLLocationManagerDelegate {
21    private let manager = CLLocationManager()
22    private var session: CLServiceSession?
23    private var watching: Task<Void, Never>?
24    /// The session's last state in the log, kept across renewals so a
25    /// renewal that changes nothing isn't logged.
26    private var loggedState: String?
27    private let log = EventLog.shared.category("Location")
28
29    /// Takes the session at once, if 'Always' is granted. Created before
30    /// launch finishes, both to take the session within Core Location's
31    /// grace period and to have a delegate for the location change that
32    /// launched the app.
33    override init() {
34        super.init()
35        manager.delegate = self
36        refresh()
37    }
38
39    /// Starts or stops holding the session and watching for changes to
40    /// match the authorisation. `renewing` replaces a held session, as
41    /// coming to the foreground should: a session started then always takes
42    /// effect, where one taken in the background may not have.
43    func refresh(renewing: Bool = false) {
44        guard manager.authorizationStatus == .authorizedAlways else {
45            stop()
46            return
47        }
48        if session == nil {
49            log.info("Holding a location session for 'Always'")
50        }
51        if session == nil || renewing {
52            hold()
53        }
54        manager.startMonitoringSignificantLocationChanges()
55    }
56
57    /// Takes a new session in place of any held, and logs whether it's in
58    /// effect: one that isn't says it's insufficiently in use until the app
59    /// comes to the foreground.
60    private func hold() {
61        let old = session
62        let session = CLServiceSession(authorization: .always)
63        self.session = session
64        old?.invalidate()
65        watching?.cancel()
66        watching = Task {
67            do {
68                for try await diagnostic in session.diagnostics {
69                    note(Self.state(of: diagnostic))
70                }
71            } catch {}
72        }
73    }
74
75    private func stop() {
76        guard let session else { return }
77        watching?.cancel()
78        watching = nil
79        session.invalidate()
80        self.session = nil
81        loggedState = nil
82        manager.stopMonitoringSignificantLocationChanges()
83        log.info("Stopped holding a location session: no 'Always'")
84    }
85
86    private func note(_ state: String) {
87        guard state != loggedState else { return }
88        loggedState = state
89        log.info("Location session: \(state)")
90    }
91
92    private static func state(of diagnostic: CLServiceSession.Diagnostic) -> String {
93        let flags = [
94            ("insufficientlyInUse", diagnostic.insufficientlyInUse),
95            ("alwaysAuthorizationDenied", diagnostic.alwaysAuthorizationDenied),
96            ("authorizationDenied", diagnostic.authorizationDenied),
97            ("authorizationDeniedGlobally", diagnostic.authorizationDeniedGlobally),
98            ("authorizationRestricted", diagnostic.authorizationRestricted),
99            ("serviceSessionRequired", diagnostic.serviceSessionRequired),
100        ]
101        let set = flags.filter(\.1).map(\.0)
102        return set.isEmpty ? "in effect" : "held back, \(set.joined(separator: ", "))"
103    }
104
105    // The manager was made on the main thread, so it calls back there.
106
107    nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
108        MainActor.assumeIsolated { refresh() }
109    }
110
111    /// The fix itself isn't needed: Core Location keeps the latest for the
112    /// next capture.
113    nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}
114
115    nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {}
116}