tennis25 tennis25 - 1 month ago 19
iOS Question

iOS app crashes on launch screen, location is requested after app crashes (Xcode 8.3.3)

When I run my iOS app from Xcode to the iOS simulator or to my physical device, the app crashes within a couple of seconds. As the app then enters the background and I am returned to the iPhone homescreen, the Alert View asking for permission to use my location pops up but then quickly disappears before I can select an answer.

After declaring and initializing a CLLocationManager called "locationManager", I believe that the errors are triggered from these statements:

locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()


The main error that appears in the console logs is:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didFailWithError:'


I have set my usage description with the "NSLocationWhenInUseUsageDescription", so that my app can present to the user what their location will be used for, thus giving the app permission to access their location. Is there anything else I am missing that may contribute to this error?

In order to get the location of the user, do I only need it request it through adding the "NSLocationWhenInUseUsageDescription" key to the Info.plist file, or are there more measures I need to approach?

Answer Source

To solve your problem:

Create a class like, and override the methods as below:

class LocationDelegate : NSObject, CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
         // here you will receive your location updates on `locations` parameter

    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        // if something goes wrong comes to here
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
       // here you can monitor the authorization status changes
    }

}

Create a global instance of this class wherever you want.

let locationDelegate: LocationDelegate = LocationDelegate()

Then before you ask permission set the delegate:

locationManager.delegate = locationDelegate