Search code examples
swiftmapkitxcode9mapkitannotation

How to set up alerts from Annotation Callout Xcode 9


I am attempting to have a button in an annotation callout have an alert when pressed. The compiler throws no errors, but the program never seems to enter that particular mapView function.

Here is the function:

extension ViewController{
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    // 2
    guard let annotation = annotation as? parkingZone else { return nil }
    // 3
    let identifier = "marker"
    var view: MKMarkerAnnotationView
    // 4
    if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
        as? MKMarkerAnnotationView {
        dequeuedView.annotation = annotation
        view = dequeuedView
    } else {
        // 5
        view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        view.markerTintColor = .black
        view.canShowCallout = true
        view.calloutOffset = CGPoint(x: -5, y: 5)
        view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    }
    return view
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, vc: UIViewController, calloutAccessoryControlTapped control: UIControl) {
    print("Button Press")
    let alertController = UIAlertController(title: "Hello", message: "This will start alerts", preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
    alertController.addAction(cancelAction)
    vc.present(alertController, animated: true, completion: nil)
}
}

Solution

  • Check the signature of your calloutAccessoryControlTapped method, you have an extra parameter for vc: UIViewController. Your method needs to match the delegate method's signature exactly.

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        print("Button Press")
        let alertController = UIAlertController(title: "Hello", message: "This will start alerts", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }