I am getting user's current location in my SwiftUI app. To get the latitude and longitude, I am using following code onAppear() of my view:
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation: CLLocation?
switch locManager.authorizationStatus {
case .notDetermined, .restricted, .denied:
print("lat long will nil")
case .authorizedAlways, .authorizedWhenInUse:
let lati = currentLocation?.coordinate.latitude
let long = currentLocation?.coordinate.longitude
print("lat: \(lati) long: \(long)")
@unknown default:
print("error getting location")
}
And this is printing:
lat: nil long: nil
I am not getting why is it not getting the current location. My info.plist is:
Does anyone knows what's the issue?
I got the answer to my question and it is that you have to just add one line in case .authorizedAlways, .authorizedWhenInUse:
currentLocation = locManager.location
The whole code will:
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation: CLLocation?
switch locManager.authorizationStatus {
case .notDetermined, .restricted, .denied:
print("lat long will nil")
case .authorizedAlways, .authorizedWhenInUse:
currentLocation = locManager.location
let lati = currentLocation?.coordinate.latitude
let long = currentLocation?.coordinate.longitude
print("lat: \(lati) long: \(long)")
@unknown default:
print("error getting location")
}