apple_kit

Apple-native services for Radroots iOS and macOS apps
git clone https://radroots.dev/git/apple_kit.git
Log | Files | Refs | README | LICENSE

RadrootsPermissionLocation.swift (9791B)


      1 import Foundation
      2 
      3 public enum RadrootsPermissionKind: String, Sendable, Equatable, Hashable, CaseIterable {
      4     case notifications
      5     case camera
      6     case photos
      7     case microphone
      8     case location
      9 }
     10 
     11 public enum RadrootsPermissionStatus: String, Sendable, Equatable, Hashable {
     12     case notDetermined
     13     case authorized
     14     case denied
     15     case restricted
     16     case limited
     17     case unavailable
     18     case unsupported
     19 }
     20 
     21 public struct RadrootsPermissionSnapshot: Sendable, Equatable, Hashable {
     22     public let kind: RadrootsPermissionKind
     23     public let status: RadrootsPermissionStatus
     24     public let observedAt: Date
     25 
     26     public init(kind: RadrootsPermissionKind, status: RadrootsPermissionStatus, observedAt: Date) {
     27         self.kind = kind
     28         self.status = status
     29         self.observedAt = observedAt
     30     }
     31 }
     32 
     33 public protocol RadrootsPermissionStatusProvider: Sendable {
     34     func snapshot(for kind: RadrootsPermissionKind) async throws -> RadrootsPermissionSnapshot
     35     func snapshots(for kinds: [RadrootsPermissionKind]) async throws -> [RadrootsPermissionSnapshot]
     36 }
     37 
     38 extension RadrootsPermissionStatusProvider {
     39     public func snapshots(for kinds: [RadrootsPermissionKind]) async throws
     40         -> [RadrootsPermissionSnapshot]
     41     {
     42         var snapshots: [RadrootsPermissionSnapshot] = []
     43         snapshots.reserveCapacity(kinds.count)
     44         for kind in kinds {
     45             try await snapshots.append(snapshot(for: kind))
     46         }
     47         return snapshots
     48     }
     49 }
     50 
     51 public enum RadrootsLocationAuthorization: String, Sendable, Equatable, Hashable {
     52     case notDetermined
     53     case authorizedWhenInUse
     54     case authorizedAlways
     55     case denied
     56     case restricted
     57     case unavailable
     58     case unsupported
     59 
     60     public var permissionStatus: RadrootsPermissionStatus {
     61         switch self {
     62         case .notDetermined:
     63             .notDetermined
     64         case .authorizedWhenInUse:
     65             .authorized
     66         case .authorizedAlways:
     67             .authorized
     68         case .denied:
     69             .denied
     70         case .restricted:
     71             .restricted
     72         case .unavailable:
     73             .unavailable
     74         case .unsupported:
     75             .unsupported
     76         }
     77     }
     78 }
     79 
     80 public struct RadrootsLocationServicesAvailability: Sendable, Equatable, Hashable {
     81     public let locationServicesEnabled: Bool
     82     public let authorization: RadrootsLocationAuthorization
     83 
     84     public init(locationServicesEnabled: Bool, authorization: RadrootsLocationAuthorization) {
     85         self.locationServicesEnabled = locationServicesEnabled
     86         self.authorization = authorization
     87     }
     88 
     89     public var canRequestWhenInUseAuthorization: Bool {
     90         locationServicesEnabled && authorization == .notDetermined
     91     }
     92 
     93     public var canRequestCurrentLocation: Bool {
     94         locationServicesEnabled
     95             && (authorization == .authorizedWhenInUse || authorization == .authorizedAlways)
     96     }
     97 }
     98 
     99 public struct RadrootsLocationCoordinate: Sendable, Equatable, Hashable {
    100     public let latitude: Double
    101     public let longitude: Double
    102 
    103     public init(latitude: Double, longitude: Double) throws {
    104         guard latitude.isFinite, (-90.0...90.0).contains(latitude) else {
    105             throw RadrootsLocationServicesError.invalidRequest
    106         }
    107         guard longitude.isFinite, (-180.0...180.0).contains(longitude) else {
    108             throw RadrootsLocationServicesError.invalidRequest
    109         }
    110         self.latitude = latitude
    111         self.longitude = longitude
    112     }
    113 }
    114 
    115 public struct RadrootsLocationReading: Sendable, Equatable, Hashable {
    116     public let coordinate: RadrootsLocationCoordinate
    117     public let horizontalAccuracyMeters: Double
    118     public let altitudeMeters: Double?
    119     public let verticalAccuracyMeters: Double?
    120     public let speedMetersPerSecond: Double?
    121     public let courseDegrees: Double?
    122     public let capturedAt: Date
    123 
    124     public init(
    125         coordinate: RadrootsLocationCoordinate,
    126         horizontalAccuracyMeters: Double,
    127         altitudeMeters: Double? = nil,
    128         verticalAccuracyMeters: Double? = nil,
    129         speedMetersPerSecond: Double? = nil,
    130         courseDegrees: Double? = nil,
    131         capturedAt: Date
    132     ) throws {
    133         self.coordinate = coordinate
    134         self.horizontalAccuracyMeters = try Self.normalizedNonNegativeFinite(
    135             horizontalAccuracyMeters,
    136             field: "horizontal accuracy"
    137         )
    138         self.altitudeMeters = try Self.normalizedOptionalFinite(altitudeMeters, field: "altitude")
    139         self.verticalAccuracyMeters = try Self.normalizedOptionalNonNegativeFinite(
    140             verticalAccuracyMeters,
    141             field: "vertical accuracy"
    142         )
    143         self.speedMetersPerSecond = try Self.normalizedOptionalNonNegativeFinite(
    144             speedMetersPerSecond,
    145             field: "speed"
    146         )
    147         self.courseDegrees = try Self.normalizedOptionalCourse(courseDegrees)
    148         guard capturedAt.timeIntervalSinceReferenceDate.isFinite else {
    149             throw RadrootsLocationServicesError.invalidRequest
    150         }
    151         self.capturedAt = capturedAt
    152     }
    153 
    154     public func age(relativeTo now: Date) throws -> TimeInterval {
    155         guard now.timeIntervalSinceReferenceDate.isFinite else {
    156             throw RadrootsLocationServicesError.invalidRequest
    157         }
    158         return now.timeIntervalSince(capturedAt)
    159     }
    160 
    161     public func isFresh(relativeTo now: Date, maximumAgeSeconds: TimeInterval) throws -> Bool {
    162         let normalizedMaximumAge = try Self.normalizedNonNegativeFinite(
    163             maximumAgeSeconds, field: "maximum age")
    164         let currentAge = try age(relativeTo: now)
    165         return currentAge >= 0 && currentAge <= normalizedMaximumAge
    166     }
    167 
    168     public static func normalizedNonNegativeFinite(_ value: Double, field: String) throws -> Double
    169     {
    170         guard value.isFinite, value >= 0 else {
    171             throw RadrootsLocationServicesError.invalidRequest
    172         }
    173         return value
    174     }
    175 
    176     public static func normalizedOptionalFinite(_ value: Double?, field: String) throws -> Double? {
    177         guard let value else {
    178             return nil
    179         }
    180         guard value.isFinite else {
    181             throw RadrootsLocationServicesError.invalidRequest
    182         }
    183         return value
    184     }
    185 
    186     public static func normalizedOptionalNonNegativeFinite(_ value: Double?, field: String) throws
    187         -> Double?
    188     {
    189         guard let value else {
    190             return nil
    191         }
    192         return try normalizedNonNegativeFinite(value, field: field)
    193     }
    194 
    195     public static func normalizedOptionalCourse(_ value: Double?) throws -> Double? {
    196         guard let value else {
    197             return nil
    198         }
    199         guard value.isFinite, (0.0..<360.0).contains(value) else {
    200             throw RadrootsLocationServicesError.invalidRequest
    201         }
    202         return value
    203     }
    204 }
    205 
    206 public struct RadrootsCurrentLocationRequest: Sendable, Equatable, Hashable {
    207     public let timeoutSeconds: TimeInterval
    208     public let desiredAccuracyMeters: Double?
    209     public let maximumCachedReadingAgeSeconds: TimeInterval?
    210 
    211     public init(
    212         timeoutSeconds: TimeInterval = 12,
    213         desiredAccuracyMeters: Double? = nil,
    214         maximumCachedReadingAgeSeconds: TimeInterval? = nil
    215     ) throws {
    216         guard timeoutSeconds > 0,
    217             RadrootsAppleTimeConversion.nanoseconds(timeoutSeconds) != nil
    218         else {
    219             throw RadrootsLocationServicesError.invalidRequest
    220         }
    221         self.timeoutSeconds = timeoutSeconds
    222         self.desiredAccuracyMeters =
    223             try RadrootsLocationReading.normalizedOptionalNonNegativeFinite(
    224                 desiredAccuracyMeters,
    225                 field: "desired accuracy"
    226             )
    227         self.maximumCachedReadingAgeSeconds =
    228             try RadrootsLocationReading.normalizedOptionalNonNegativeFinite(
    229                 maximumCachedReadingAgeSeconds,
    230                 field: "maximum cached reading age"
    231             )
    232     }
    233 }
    234 
    235 public struct RadrootsCurrentLocationResult: Sendable, Equatable, Hashable {
    236     public let reading: RadrootsLocationReading
    237     public let authorization: RadrootsLocationAuthorization
    238     public let servedFromCache: Bool
    239 
    240     public init(
    241         reading: RadrootsLocationReading,
    242         authorization: RadrootsLocationAuthorization,
    243         servedFromCache: Bool = false
    244     ) throws {
    245         guard authorization == .authorizedWhenInUse || authorization == .authorizedAlways else {
    246             throw RadrootsLocationServicesError.invalidRequest
    247         }
    248         self.reading = reading
    249         self.authorization = authorization
    250         self.servedFromCache = servedFromCache
    251     }
    252 }
    253 
    254 public enum RadrootsLocationServicesError: Error, Equatable, Sendable {
    255     case invalidRequest
    256     case permissionDenied
    257     case unavailable
    258     case timeout
    259     case cancelled
    260     case transientFailure
    261     case permanentFailure
    262 }
    263 
    264 extension RadrootsLocationServicesError: LocalizedError {
    265     public var errorDescription: String? {
    266         switch self {
    267         case .invalidRequest: "The location request is invalid."
    268         case .permissionDenied: "Location permission was denied."
    269         case .unavailable: "Location services are unavailable."
    270         case .timeout: "The location request timed out."
    271         case .cancelled: "The location request was cancelled."
    272         case .transientFailure: "Location could not be determined temporarily."
    273         case .permanentFailure: "Location could not be determined."
    274         }
    275     }
    276 }
    277 
    278 public protocol RadrootsLocationServices: Sendable {
    279     func currentAvailability() async -> RadrootsLocationServicesAvailability
    280     func requestWhenInUseAuthorization() async throws -> RadrootsLocationAuthorization
    281     func currentLocation(_ request: RadrootsCurrentLocationRequest) async throws
    282         -> RadrootsCurrentLocationResult
    283 }