Reportage/Services/BackgroundLocation.swift (4848B)
1import CoreLocation
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
25
26 private var loggedState: String?
27 private let log = EventLog.shared.category("Location")
28
29
30
31
32
33 override init() {
34 super.init()
35 manager.delegate = self
36 refresh()
37 }
38
39
40
41
42
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
58
59
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
106
107 nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
108 MainActor.assumeIsolated { refresh() }
109 }
110
111
112
113 nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}
114
115 nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {}
116}