Following my comment on Craig's answer, I think the solution might look something like this:
import MapKit extension MKMapView { func containsAnnotation(annotation: MKAnnotation) -> Bool { if let existingAnnotations = self.annotations as? [MKAnnotation] { for existingAnnotation in existingAnnotations { if existingAnnotation.title == annotation.title && existingAnnotation.coordinate.latitude == annotation.coordinate.latitude && existingAnnotation.coordinate.longitude == annotation.coordinate.longitude { return true } } } return false } }
This code allows you to check if mapView contains this annotation. Use this in the for loop in all of your annotations:
for annotation in annotations { if mapView.containsAnnotation(annotation) { // do nothing } else { mapView.addAnnotation(annotation) }
PS: this works well if you need to add new annotations to mapView. But if you also need to delete entries, you may need to do the opposite: make sure that every existing annotation exists in a new array of annotations; if not, delete it. Or you can delete everything and add everything again (but then you will have an animated change ...)
Frรฉdรฉric adda
source share