Search code examples
iosmkmapviewswift4mkannotationmkannotationview

didSelect mapView annotation not working properly


When I tap the map annotation it will display the more information about the pin.

On my first tap attempt ,when I tap the map annotation it will run successfully and it will display the correct information but when I hit back button and do my second tap attempt to the same pin the fatal error occured and its saying that 'Unexpectedly Found nil while unwrapping and optional value',

based on my observation and I made some troubleshooting and debugging, I found out that the fatal error only occurred when I didn't tap to the map first before I tap the map pin OR if I don't tap different pin (if I tap the same pin for the second attempt without tapping the map first error occurred)

MyAnnotations Class:

import MapKit

class MyAnnotations: NSObject,MKAnnotation{

    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    var img: String?
    var court_id: Int?
    var class_name: String?

    init(coordinate:CLLocationCoordinate2D, title: String?, subtitle: 
    String?, img:String?, court_id: Int?, class_name: String?){
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
        self.img = img
        self.court_id = court_id
        self.class_name = class_name

        super.init()
    }
}

My func mapView(_:didSelect:):

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    let ibp = view.annotation as? MyAnnotations
    print(ibp!)
    ibp_id = (ibp?.court_id)!
    IdentifierCell = "pin_IBP"
    performSegue(withIdentifier: "map_ibp_info", sender: self)
}

Solution

  • TRY THE FOLLOWING CODE:

    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
        if view.annotation is MKUserLocation {
            return
        }
    
        let ibp = view.annotation as? MyAnnotations
        print(ibp!)
        ibp_id = (ibp?.court_id)!
        IdentifierCell = "pin_IBP"
        performSegue(withIdentifier: "map_ibp_info", sender: self)
    }