Search code examples
swiftmapkitmkmapviewdelegate

MapView doesn't show Annotations after adding viewForAnnotations


so I am using MapKit for the first time and I am trying to show annotations with a callout.

The annotations appear but as soon as I add the delegate function viewFor annotation (func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {}) the annotations do not appear anymore. Is there anything I am missing in that function ?

Edit

I forgot to mention that the View Controller is the delegate of MKMapViewDelegate

@objc func addAnnotationOnLongPress(gesture: UILongPressGestureRecognizer) {

        if gesture.state == .ended {
            let point = gesture.location(in: self.mapView)
            let coordinate = self.mapView.convert(point, toCoordinateFrom: self.mapView)
            //Now use this coordinate to add annotation on map.
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate

            usf.fetchJSON(urlString: usf.setNewLocation(lat: annotation.coordinate.latitude, lon: annotation.coordinate.longitude)) { (data, success) in
                if success {
                    annotation.title = data?.name
                    annotation.subtitle = "HAa"
                } else {
                    let alertUI = self.usf.createAlertOK(title: "Something went wrong!", message: "Cannot get the current weather! \n Check your connectivity or try again later")
                    self.present(alertUI, animated: true, completion: nil)
                }
            }
            let previousAnnotations = self.mapView.annotations
            if !previousAnnotations.isEmpty{
              self.mapView.removeAnnotation(previousAnnotations[0])
            }
            self.mapView.addAnnotation(annotation)
        }        
    }



    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            return nil
        }
        print("in viewFor annotation") // prints out
        let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "TempAnnotationView")
        annotationView.canShowCallout = true
        annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        self.mapView.showAnnotations(mapView.annotations, animated: false)
        return annotationView
    }


Solution

  • You are instantiating a MKAnnotationView. If you have some custom image, then set the image property of this MKAnnotationView. Or, easier, just use MKPinAnnotationView or MKMarkerAnnotationView instead.

    And as Sh_Kahn noted, make sure you create you annotation inside the closure, not after it.