RadrootsAppleLocationServices.swift (14094B)
1 import Foundation 2 3 #if canImport(CoreLocation) 4 @preconcurrency import CoreLocation 5 #endif 6 7 public struct RadrootsAppleLocationServicesAdapters: Sendable { 8 public let now: @Sendable () -> Date 9 public let locationServicesEnabled: @Sendable () -> Bool 10 public let authorizationStatus: @Sendable () -> RadrootsLocationAuthorization 11 public let requestWhenInUseAuthorization: 12 @Sendable (TimeInterval) async throws -> RadrootsLocationAuthorization 13 public let requestCurrentLocation: 14 @Sendable (RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading 15 16 public init( 17 now: @escaping @Sendable () -> Date = Date.init, 18 locationServicesEnabled: @escaping @Sendable () -> Bool, 19 authorizationStatus: @escaping @Sendable () -> RadrootsLocationAuthorization, 20 requestWhenInUseAuthorization: 21 @escaping @Sendable (TimeInterval) async throws -> RadrootsLocationAuthorization, 22 requestCurrentLocation: 23 @escaping @Sendable (RadrootsCurrentLocationRequest) async throws -> 24 RadrootsLocationReading 25 ) { 26 self.now = now 27 self.locationServicesEnabled = locationServicesEnabled 28 self.authorizationStatus = authorizationStatus 29 self.requestWhenInUseAuthorization = requestWhenInUseAuthorization 30 self.requestCurrentLocation = requestCurrentLocation 31 } 32 33 public static var live: Self { 34 #if canImport(CoreLocation) 35 Self( 36 locationServicesEnabled: { 37 CLLocationManager.locationServicesEnabled() 38 }, 39 authorizationStatus: { 40 authorization( 41 for: CLLocationManager().authorizationStatus, 42 locationServicesEnabled: CLLocationManager.locationServicesEnabled() 43 ) 44 }, 45 requestWhenInUseAuthorization: { timeoutSeconds in 46 try await RadrootsCoreLocationAuthorizationSession().start( 47 timeoutSeconds: timeoutSeconds) 48 }, 49 requestCurrentLocation: { request in 50 try await RadrootsCoreLocationReadingSession().start(request: request) 51 } 52 ) 53 #else 54 Self( 55 locationServicesEnabled: { false }, 56 authorizationStatus: { .unsupported }, 57 requestWhenInUseAuthorization: { _ in 58 throw RadrootsLocationServicesError.unavailable 59 }, 60 requestCurrentLocation: { _ in 61 throw RadrootsLocationServicesError.unavailable 62 } 63 ) 64 #endif 65 } 66 67 #if canImport(CoreLocation) 68 public static func authorization( 69 for status: CLAuthorizationStatus, 70 locationServicesEnabled: Bool 71 ) -> RadrootsLocationAuthorization { 72 guard locationServicesEnabled else { 73 return .unavailable 74 } 75 switch status { 76 case .notDetermined: 77 return .notDetermined 78 case .restricted: 79 return .restricted 80 case .denied: 81 return .denied 82 case .authorizedAlways: 83 return .authorizedAlways 84 #if os(iOS) 85 case .authorizedWhenInUse: 86 return .authorizedWhenInUse 87 #endif 88 @unknown default: 89 return .unavailable 90 } 91 } 92 #endif 93 } 94 95 public final class RadrootsAppleLocationServices: RadrootsLocationServices, Sendable { 96 private let adapters: RadrootsAppleLocationServicesAdapters 97 98 public init(adapters: RadrootsAppleLocationServicesAdapters = .live) { 99 self.adapters = adapters 100 } 101 102 public func currentAvailability() async -> RadrootsLocationServicesAvailability { 103 let enabled = adapters.locationServicesEnabled() 104 return RadrootsLocationServicesAvailability( 105 locationServicesEnabled: enabled, 106 authorization: enabled ? adapters.authorizationStatus() : .unavailable 107 ) 108 } 109 110 public func requestWhenInUseAuthorization() async throws -> RadrootsLocationAuthorization { 111 let availability = await currentAvailability() 112 guard availability.locationServicesEnabled else { 113 throw RadrootsLocationServicesError.unavailable 114 } 115 switch availability.authorization { 116 case .notDetermined: 117 do { 118 return try await adapters.requestWhenInUseAuthorization(12) 119 } catch let error as RadrootsLocationServicesError { 120 throw error 121 } catch { 122 throw RadrootsLocationServicesError.permanentFailure 123 } 124 case .authorizedWhenInUse: 125 return .authorizedWhenInUse 126 case .authorizedAlways: 127 return .authorizedAlways 128 case .denied: 129 throw RadrootsLocationServicesError.permissionDenied 130 case .restricted: 131 throw RadrootsLocationServicesError.permissionDenied 132 case .unavailable: 133 throw RadrootsLocationServicesError.unavailable 134 case .unsupported: 135 throw RadrootsLocationServicesError.unavailable 136 } 137 } 138 139 public func currentLocation(_ request: RadrootsCurrentLocationRequest) async throws 140 -> RadrootsCurrentLocationResult 141 { 142 let availability = await currentAvailability() 143 guard availability.locationServicesEnabled else { 144 throw RadrootsLocationServicesError.unavailable 145 } 146 guard availability.canRequestCurrentLocation else { 147 switch availability.authorization { 148 case .denied: 149 throw RadrootsLocationServicesError.permissionDenied 150 case .restricted: 151 throw RadrootsLocationServicesError.permissionDenied 152 case .notDetermined: 153 throw RadrootsLocationServicesError.permissionDenied 154 case .unavailable: 155 throw RadrootsLocationServicesError.unavailable 156 case .unsupported: 157 throw RadrootsLocationServicesError.unavailable 158 case .authorizedWhenInUse, .authorizedAlways: 159 break 160 } 161 throw RadrootsLocationServicesError.unavailable 162 } 163 let reading: RadrootsLocationReading 164 do { 165 reading = try await adapters.requestCurrentLocation(request) 166 } catch let error as RadrootsLocationServicesError { 167 throw error 168 } catch { 169 throw RadrootsLocationServicesError.permanentFailure 170 } 171 if let maximumAgeSeconds = request.maximumCachedReadingAgeSeconds { 172 guard 173 try reading.isFresh( 174 relativeTo: adapters.now(), maximumAgeSeconds: maximumAgeSeconds) 175 else { 176 throw RadrootsLocationServicesError.transientFailure 177 } 178 } 179 return try RadrootsCurrentLocationResult( 180 reading: reading, 181 authorization: availability.authorization 182 ) 183 } 184 } 185 186 #if canImport(CoreLocation) 187 @MainActor 188 private final class RadrootsCoreLocationAuthorizationSession: NSObject, 189 @preconcurrency CLLocationManagerDelegate 190 { 191 private var continuation: CheckedContinuation<RadrootsLocationAuthorization, any Error>? 192 private var manager: CLLocationManager? 193 private var timeoutTask: Task<Void, Never>? 194 195 func start(timeoutSeconds: TimeInterval) async throws -> RadrootsLocationAuthorization { 196 guard timeoutSeconds > 0, 197 let nanoseconds = RadrootsAppleTimeConversion.nanoseconds(timeoutSeconds) 198 else { 199 throw RadrootsLocationServicesError.invalidRequest 200 } 201 return try await withTaskCancellationHandler { 202 try await withCheckedThrowingContinuation { continuation in 203 self.continuation = continuation 204 let manager = CLLocationManager() 205 self.manager = manager 206 manager.delegate = self 207 timeoutTask = Task { [weak self] in 208 try? await Task.sleep(nanoseconds: nanoseconds) 209 self?.finish(.failure(.timeout)) 210 } 211 manager.requestWhenInUseAuthorization() 212 } 213 } onCancel: { 214 Task { @MainActor [weak self] in 215 self?.finish(.failure(.cancelled)) 216 } 217 } 218 } 219 220 func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { 221 let authorization = RadrootsAppleLocationServicesAdapters.authorization( 222 for: manager.authorizationStatus, 223 locationServicesEnabled: CLLocationManager.locationServicesEnabled() 224 ) 225 guard authorization != .notDetermined else { 226 return 227 } 228 finish(.success(authorization)) 229 } 230 231 private func finish( 232 _ result: Result<RadrootsLocationAuthorization, RadrootsLocationServicesError> 233 ) { 234 guard let continuation else { 235 return 236 } 237 self.continuation = nil 238 timeoutTask?.cancel() 239 timeoutTask = nil 240 manager?.delegate = nil 241 manager = nil 242 switch result { 243 case .success(let authorization): 244 continuation.resume(returning: authorization) 245 case .failure(let error): 246 continuation.resume(throwing: error) 247 } 248 } 249 } 250 251 @MainActor 252 private final class RadrootsCoreLocationReadingSession: NSObject, 253 @preconcurrency CLLocationManagerDelegate 254 { 255 private var continuation: CheckedContinuation<RadrootsLocationReading, any Error>? 256 private var manager: CLLocationManager? 257 private var timeoutTask: Task<Void, Never>? 258 259 func start(request: RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading 260 { 261 guard let nanoseconds = RadrootsAppleTimeConversion.nanoseconds(request.timeoutSeconds) 262 else { 263 throw RadrootsLocationServicesError.invalidRequest 264 } 265 return try await withTaskCancellationHandler { 266 try await withCheckedThrowingContinuation { continuation in 267 self.continuation = continuation 268 let manager = CLLocationManager() 269 self.manager = manager 270 manager.delegate = self 271 if let desiredAccuracyMeters = request.desiredAccuracyMeters { 272 manager.desiredAccuracy = desiredAccuracyMeters 273 } 274 timeoutTask = Task { [weak self] in 275 try? await Task.sleep(nanoseconds: nanoseconds) 276 self?.finish(.failure(.timeout)) 277 } 278 manager.requestLocation() 279 } 280 } onCancel: { 281 Task { @MainActor [weak self] in 282 self?.finish(.failure(.cancelled)) 283 } 284 } 285 } 286 287 func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 288 guard let location = locations.sorted(by: { $0.timestamp < $1.timestamp }).last else { 289 finish(.failure(.transientFailure)) 290 return 291 } 292 do { 293 try finish(.success(Self.reading(from: location))) 294 } catch let error as RadrootsLocationServicesError { 295 finish(.failure(error)) 296 } catch { 297 finish(.failure(.permanentFailure)) 298 } 299 } 300 301 func locationManager(_: CLLocationManager, didFailWithError error: any Error) { 302 if let coreLocationError = error as? CLError { 303 switch coreLocationError.code { 304 case .denied: 305 finish(.failure(.permissionDenied)) 306 case .locationUnknown: 307 finish(.failure(.transientFailure)) 308 case .network: 309 finish(.failure(.transientFailure)) 310 default: 311 finish(.failure(.permanentFailure)) 312 } 313 } else { 314 finish(.failure(.permanentFailure)) 315 } 316 } 317 318 private func finish( 319 _ result: Result<RadrootsLocationReading, RadrootsLocationServicesError> 320 ) { 321 guard let continuation else { 322 return 323 } 324 self.continuation = nil 325 timeoutTask?.cancel() 326 timeoutTask = nil 327 manager?.delegate = nil 328 manager = nil 329 switch result { 330 case .success(let reading): 331 continuation.resume(returning: reading) 332 case .failure(let error): 333 continuation.resume(throwing: error) 334 } 335 } 336 337 private static func reading(from location: CLLocation) throws -> RadrootsLocationReading { 338 try RadrootsLocationReading( 339 coordinate: RadrootsLocationCoordinate( 340 latitude: location.coordinate.latitude, 341 longitude: location.coordinate.longitude 342 ), 343 horizontalAccuracyMeters: location.horizontalAccuracy, 344 altitudeMeters: location.verticalAccuracy >= 0 ? location.altitude : nil, 345 verticalAccuracyMeters: location.verticalAccuracy >= 0 346 ? location.verticalAccuracy : nil, 347 speedMetersPerSecond: location.speed >= 0 ? location.speed : nil, 348 courseDegrees: location.course >= 0 ? location.course : nil, 349 capturedAt: location.timestamp 350 ) 351 } 352 } 353 #endif