I am having a strange error and cannot figure this one out. I have made a simple weather application that updates the weather based on the users coordinates. On simulator everything runs perfect however on device I get the error seen below.
I declared my location manager in the class scope right above viewDidLoad:
let locationManager = CLLocationManager()
My viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
tableView.delegate = self
tableView.dataSource = self
currentWeather = CurrentWeather()
}
I am calling this function once the viewDidAppear:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
currentLocation = locationManager.location
Location.sharedInstance.latitude = currentLocation.coordinate.latitude
Location.sharedInstance.longitude = currentLocation.coordinate.longitude
currentWeather.downloadWeatherDetails {
self.downloadForecastData {
self.updateMainUI()
}
}
} else {
locationManager.requestWhenInUseAuthorization()
locationAuthStatus()
}
}
The error is the first line in the else statement above if the user hasn't been granted authorization yet. If you rerun the app after the crash, the weather will update just fine. Any help would be appreciated. Thank you.
UPDATE
Thanks to a suggestion in the comments I was able to fix my error. I moved the code from locationAuthStatus into the locationManager(_ manager: CLLocationManager, didChangeAuthorization.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
currentLocation = locationManager.location
Location.sharedInstance.latitude = currentLocation.coordinate.latitude
Location.sharedInstance.longitude = currentLocation.coordinate.longitude
currentWeather.downloadWeatherDetails {
self.downloadForecastData {
self.updateMainUI()
}
}
} else {
locationManager.requestWhenInUseAuthorization()
}
}
Thank you everyone for your help.