Hi,
I am trying to implement macOS application with swiftUI, In that i am trying to get current user location using following code.
import Foundation
import CoreLocation
import MapKit
class CurrentLocationManager2: NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
}
func startLocation() {
locationManager.requestAlwaysAuthorization()
// locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}else{
print ("Error Location")
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
print("authorizedAlways status is assigned")
manager.startUpdatingLocation()
}
else if status == .denied {
print("denied status is assigned")
}
else if status == .notDetermined {
print("notDetermined status is assigned")
manager.requestAlwaysAuthorization()
}
else if status == .restricted {
print("restricted status is assigned")
}
else {
print("status is not assigned")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//last
if let location = locations.first {
print("Found user's location: \(location)", "lat =", location.coordinate.latitude," long = ",location.coordinate.longitude)
LogModel.latitude = String(location.coordinate.latitude)
LogModel.longitude = String(location.coordinate.longitude)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to find user's location: \(error.localizedDescription)")
}
}
let location = CurrentLocationManager2()
location.startLocation()