Files
mowesta/ios-app/app/Arduino/ArduinoLocator.swift
T
Marcus Handte 2c788e3329
LocationBasedServices/mowesta/pipeline/head This commit looks good
Add weather station configuration to ios app.
2022-11-03 16:47:26 +01:00

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
}
}