1

I'm trying to draw a path (with MKMapView). But I have:

NSInvalidArgumentException ', reason:' *** - [NSMutableOrderedSet addObject:]: object can not be nil '.

I have this button action with a NSTimer that calls the function stop

@IBAction func startRoute(sender: UIButton) {
    // Timer stop() function
    // Each 4 seconds
    timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(ViewController.stop), userInfo: nil, repeats: true)
}

And this is my stop() function, which puts a "Start Point" and it is going adding the current location to the vector called points of type var points: [CLLocationCoordinate2D] = [] and draw the path with the addOverlay.

func stop() {
    if (self.initialFlag == 0) {
        // Put flag to 1
        self.initialFlag = 1

        // Add a Annotation
        let sourceAnnotation = MKPointAnnotation()
        sourceAnnotation.title = "Start Point"
        sourceAnnotation.coordinate = (self.locationManager.location?.coordinate)!
        self.mapView.showAnnotations([sourceAnnotation], animated: true)                        
    }

    // Get current point location
    let currentLocation = CLLocationCoordinate2DMake((self.locationManager.location?.coordinate.latitude)!,(self.locationManager.location?.coordinate.longitude)!);

    // We add points every 4 seconds then draw the map points
    self.points.append(currentLocation)


    // Draw the path

    geodesic = MKGeodesicPolyline(coordinates: &points[0], count: points.count)

    // And I have the error in this line below.
    self.mapView.addOverlay(self.geodesic, level: .AboveRoads)

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Try to get rid of force unwrapping optionals and use guard or if let syntax to unwrap it. Then check if locationManager.location.coordinate is available at the moment you call it. If it doesn't fix the problem, post updated code in the question. – invisible_hand May 17 '16 at 14:03
  • use the debugger to find out where it crashes. maybe points isn't valid and MKGeodesicPolyline isnt valid then and MKGeodesicPolyline.points is nil? – Daij-Djan May 17 '16 at 15:48
  • what is points[0] and whats geodesic.points and whats geodesic.pointCount – Daij-Djan May 17 '16 at 15:49

1 Answers1

0

Hey it looks like if you don't have enought coordinates to create MKGeodesicPolyline it throws an error, My solution was it

if points.count > 1{
   geodesic = MKGeodesicPolyline(coordinates: &points[0], count: points.count)
   self.mapView.addOverlay(self.geodesic, level: .AboveRoads)
}