0

Swift sometimes give this AppDelegate Error when try to find user location

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(0x18b3fd1b8 0x189e3455c 0x18b367bac 0x1000ffd20 0x1000fe7f4 0x1000fea30 0x193400a38 0x1934002b4 0x1933f34b8 0x18b3aaa44 0x18b3aa240 0x18b3a8538 0x18b2d62b8 0x18cd8a198 0x19131d7fc 0x191318534 0x100108078 0x18a2b95b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

This is my locationManager function:

 override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()               
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last        
    myLat = (location?.coordinate.latitude)!
    myLng = (location?.coordinate.longitude)!        
    self.locationManager.stopUpdatingLocation()
    createMarker(lat: myLat,lng: myLng,zoom: 16)        
}

Sometimes its working good but sometimes the app crashes and give this AppDelegate error. So why I get this error and How I fix it?

1 Answers1

0

You're assuming that the [CLLocation] array actually has elements, which isn't always true. Add an if let to conditionally process the location based on whether it is provided or not.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        myLat = location.coordinate.latitude
        myLng = location.coordinate.longitude
        self.locationManager.stopUpdatingLocation()
        createMarker(lat: myLat, lng: myLng, zoom: 16) 
    }
}
Andy Obusek
  • 12,614
  • 4
  • 41
  • 62