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 answers

0
Mark Maraya 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
Tushar On

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

0
fanfan 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
Marcos 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
    }
    ...
}