EntryPosition.swift (2860B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import Observation 4 @preconcurrency import CoreLocation 5 6 /// Position of the entry point, taken on the "Ready" screen: GPS does not work underwater, so the fix has to 7 /// be taken before the dive. The best fix (smallest uncertainty) is kept and written into the dive log. 8 @MainActor @Observable 9 final class EntryPosition: NSObject, CLLocationManagerDelegate { 10 enum State: Equatable { case idle, searching, denied, unavailable } 11 12 private(set) var state = State.idle 13 /// Best fix so far. 14 private(set) var fix: CLLocation? 15 16 private let manager = CLLocationManager() 17 18 override init() { 19 super.init() 20 manager.delegate = self 21 manager.desiredAccuracy = kCLLocationAccuracyBest 22 } 23 24 /// Asks for the permission ahead of time (introduction), without taking a fix. 25 func requestAuthorization() { 26 if manager.authorizationStatus == .notDetermined { manager.requestWhenInUseAuthorization() } 27 } 28 29 func start() { 30 fix = nil 31 switch manager.authorizationStatus { 32 case .denied, .restricted: 33 state = .denied 34 case .notDetermined: 35 state = .searching 36 manager.requestWhenInUseAuthorization() 37 default: 38 state = .searching 39 manager.startUpdatingLocation() 40 } 41 } 42 43 func stop() { 44 manager.stopUpdatingLocation() 45 if state == .searching { state = .idle } 46 } 47 48 nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { 49 let status = manager.authorizationStatus 50 Task { @MainActor in 51 guard self.state == .searching || self.state == .denied else { return } 52 switch status { 53 case .denied, .restricted: self.state = .denied 54 case .notDetermined: break 55 default: 56 self.state = .searching 57 self.manager.startUpdatingLocation() 58 } 59 } 60 } 61 62 nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 63 // Recent and plausible fixes only. 64 let usable = locations.filter { $0.horizontalAccuracy >= 0 && $0.timestamp.timeIntervalSinceNow > -120 } 65 guard let best = usable.min(by: { $0.horizontalAccuracy < $1.horizontalAccuracy }) else { return } 66 Task { @MainActor in 67 guard self.state == .searching else { return } 68 if self.fix.map({ best.horizontalAccuracy <= $0.horizontalAccuracy }) ?? true { self.fix = best } 69 } 70 } 71 72 nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) { 73 let denied = (error as? CLError)?.code == .denied 74 Task { @MainActor in 75 if denied { self.state = .denied } 76 } 77 } 78 }