74 lines
2.2 KiB
Swift
74 lines
2.2 KiB
Swift
//
|
|
// ArduinoLocator.swift - A utility class to implement one-shot
|
|
// localization using core location.
|
|
//
|
|
// Created by Marcus Handte on 03.11.22.
|
|
//
|
|
|
|
import Foundation
|
|
import CoreLocation
|
|
|
|
class ArduinoLocator: NSObject, ObservableObject, CLLocationManagerDelegate {
|
|
|
|
let locationManager = CLLocationManager()
|
|
|
|
var localizing = false { willSet { objectWillChange.send() }}
|
|
|
|
var disabled = false { willSet { objectWillChange.send() }}
|
|
|
|
private var listener: ((Double, Double) -> Void)?
|
|
|
|
override init() {
|
|
super.init()
|
|
locationManager.desiredAccuracy = 10
|
|
locationManager.delegate = self
|
|
disabled = locationManager.authorizationStatus == .denied
|
|
}
|
|
|
|
func setListener(_ listener: @escaping (Double, Double) -> Void) {
|
|
self.listener = listener
|
|
localizing = true
|
|
if locationManager.authorizationStatus != .authorizedWhenInUse &&
|
|
locationManager.authorizationStatus != .authorizedAlways {
|
|
locationManager.requestWhenInUseAuthorization()
|
|
} else {
|
|
locationManager.requestLocation()
|
|
}
|
|
}
|
|
|
|
func clearListener() {
|
|
self.listener = nil
|
|
localizing = false
|
|
locationManager.stopUpdatingLocation()
|
|
}
|
|
|
|
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
|
|
disabled = locationManager.authorizationStatus == .denied
|
|
if listener != nil && (manager.authorizationStatus == .authorizedWhenInUse ||
|
|
manager.authorizationStatus == .authorizedAlways) {
|
|
manager.requestLocation()
|
|
} else {
|
|
localizing = false
|
|
listener = nil
|
|
}
|
|
}
|
|
|
|
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
|
if let location = locations.last {
|
|
let lat = location.coordinate.latitude
|
|
let lon = location.coordinate.longitude
|
|
if let l = listener {
|
|
l(lon, lat);
|
|
listener = nil
|
|
localizing = false
|
|
}
|
|
}
|
|
}
|
|
|
|
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
|
|
listener = nil
|
|
localizing = false
|
|
}
|
|
|
|
}
|