I want to retrieve the location of the user by getting their coordinates.
I tried retrieving it via CLLocationManager
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
@Published var location: CLLocation?
@Published var longtitude: CLLocationDegrees?
@Published var latitude: CLLocationDegrees?
override init() {
super.init()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingHeading()
locationManager.delegate = self
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last
else { return }
DispatchQueue.main.async {
self.location = location
self.longtitude = location.coordinate.longitude
self.latitude = location.coordinate.latitude
}
}
}
The last few lines in the extension were what I was having trouble with. The results I got for location.coordinate.longitude
was nil
, and the same thing happens for latitude when I print it out. I need these two values, so I could place it as my MKPlacement
in MapKit
Keep in mind that I updated my info.plist
appropriately for privacy authorization.
Any help would be greatly appreciated :)