Pietro Messineo
Pietro Messineo

Reputation: 837

Remove annotation from Map - Swift

I'm in trouble. I created a custom class for my MKPointAnnotation that is containing "identifier".

Now I want to compare the identifier and if both of the identifiers are the same I want to remove the annotation.

At the moment I have this code that is checking if both annotation.title and user.username are the same but, I wish to change it with: annotation.identifier and user.id.

 for annotation in self.mapView.annotations {
                    if let title = annotation.title, title == user.username {
                        self.mapView.removeAnnotation(annotation)
                    }

                }

For what about the custom class of the annotation is the following:

   class MyAnnotation: MKPointAnnotation {

    var identifier: String!
}

And for the creation of the annotation:

let annotation = MyAnnotation()
                    annotation.title = user.username
                    annotation.subtitle = user.job
                    annotation.identifier = user.email
                    annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(user.latitude ?? "0"))!, longitude: (Double(user.longitude ?? "0"))!)

                    self.mapView.addAnnotation(annotation)

Upvotes: 0

Views: 721

Answers (1)

fabcarvalhal
fabcarvalhal

Reputation: 36

You will have to cast the annotation to MyAnnotation before perform your code. Try something like this:


 for annotation in self.mapView.annotations {
      if let annotation = annotation as? MyAnnotation, annotation.identifier == user.id {
          self.mapView.removeAnnotation(annotation)
      }
 }

Hope this helps.

Upvotes: 2

Related Questions