import CoreLocation import SwiftUI class LocationService: NSObject, ObservableObject { @Published var currentLocation: CLLocation? @Published var authorizationStatus: CLAuthorizationStatus = .notDetermined @Published var error: String? private let locationManager = CLLocationManager() override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters authorizationStatus = locationManager.authorizationStatus } func requestPermission() { locationManager.requestWhenInUseAuthorization() } func requestLocation() { guard authorizationStatus == .authorizedWhenInUse || authorizationStatus == .authorizedAlways else { requestPermission() return } locationManager.requestLocation() } func hasPermission() -> Bool { return authorizationStatus == .authorizedWhenInUse || authorizationStatus == .authorizedAlways } } // MARK: - CLLocationManagerDelegate extension LocationService: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLocation = locations.last } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { self.error = error.localizedDescription } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { authorizationStatus = manager.authorizationStatus if hasPermission() { requestLocation() } } }