Error: Could not cast value of type NSKVONotifying_MKUserLocation to Park_View.AttractionAnnotation

2.6k Views Asked by At

When using this func:

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    let annotationView = AttractionAnnotationView(annotation: annotation, reuseIdentifier: "Attraction")
    annotationView.canShowCallout = true
    return annotationView
}

This error occured:

Could not cast value of type 'NSKVONotifying_MKUserLocation' (0x7e8a62b0) to 'Park_View.AttractionAnnotation' (0xf7948).

It is working well but when I try to add CoreLocation to find the user location to my code I start having this error.

4

There are 4 best solutions below

0
On BEST ANSWER

I found out that MKUserLocation is an annotation too.

Here is the solution that I came out with and it solve the error.

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if (annotation is MKUserLocation) {
        return nil
    }
    else {
        let annotationView = AttractionAnnotationView(annotation: annotation, reuseIdentifier: "Attraction")
        annotationView.canShowCallout = true
        return annotationView
    }
}
0
On

possibly the function AttractionAnnotationView returns MKUserLocation object instead of a AttractionAnnotation object.

0
On

Do you have a custom overridden isEqual() function in your AttractionAnnotation class? If so, check that it is not casting the compared object (the function parameter) to an AttractionAnnotation before comparison.

0
On

Same thing happens in Xcode 10.2 when you click/tap on user Location ... so try something like this:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if (view.annotation is MKUserLocation) {
        return
    }
    ...
}