The call of requestWhenInUseAuthorization method is ignored in simulator.
The required description is set:
Features -> Location -> Custom Location
is also set
now I can't get any further here, maybe someone can help
final class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var lastKnownLocation: CLLocationCoordinate2D?
@Published var authorizationStatus: CLAuthorizationStatus = .notDetermined
private var locationManager = CLLocationManager()
override init() {
super.init()
self.locationManager.delegate = self
}
func requestLocation() {
switch locationManager.authorizationStatus {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
default:
print("Location access denied or restricted")
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.authorizationStatus = status
if status == .authorizedWhenInUse || status == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastKnownLocation = locations.first?.coordinate
locationManager.stopUpdatingLocation()
}
}
extension CLLocationCoordinate2D: Equatable {
public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
}
}
View class
struct RegistrationInfoView: View {
@StateObject private var locationManager = LocationManager()
@State private var showSuccessView = false
@State private var showErrorView = false
@Binding var state: RegistrationState
var body: some View {
VStack {
Spacer()
VStack {
Text("Some info")
.font(.system(size: 16, weight: .regular))
.padding()
//...
}
Spacer()
ButtonFilled("Next") {
locationManager.requestLocation()
}
}
.onChange(of: locationManager.lastKnownLocation) { old, newLocation in
if newLocation != nil {
showSuccessView = true
} else {
showErrorView = true
}
}
.fullScreenCover(isPresented: $showSuccessView) {
Text("Success")
}
.fullScreenCover(isPresented: $showErrorView) {
Text("Error")
}
}
}
Since both NSLocationUsageDescription
and NSLocationAlwaysUsageDescription
were deprecated. I think you're missing NSLocationWhenInUseUsageDescription
from your Plist file.
Check its again to ensure these keys are added: