I have an userAlertAnnotationArray: [MKAnnotations]
that gets entries from data retrieved from Firebase. The deleting part is working perfectly with posts in Firebase and entries in the array, but it fails when deleting the selected MKAnnotation from the map. It deletes from the map the wrong Annotation.
If I exit mapVC to the menuVC and reenter mapVC that the right annotation is gone.
After a few tries, I noticed it because I get an out of range error only if i re-enter mapVC. I don't want to call the viewDiedLoad() function to refresh the view because that would be a new read per entry from Firebase every time an annotation gets deleted.
Can you see where I made a coding mistake? The updating showed annotation that fails, userAlertAnnotationArray gets the annotation removed. Please let me know if you need to see more code or other functions. Thanks in advance. This is the didSelect function:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let alertController = UIAlertController(title: "User Alert", message: "Delete selected Alert?", preferredStyle: .alert)
// Create OK button
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
var selectedAnnotation = view.annotation
if let annotation = view.annotation as? UserAlert {
let key = annotation.firebaseKey
let index = (self.mapView.annotations as NSArray).index(of: annotation)
self.userAlertNotificationArray.remove(at: index)
print(" New alert array after deliting is : \(self.userAlertNotificationArray)" )
print("post to remove key is: \(String(describing: key!))")
self.ref?.child("Community").child("Alert Notifications").child("\(String(describing: annotation.firebaseKey!))").removeValue()
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(self.userAlertNotificationArray)
// self.viewDidLoad()
}
// print("Ok button tapped")
}
alertController.addAction(OKAction)
// Create Cancel button
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in
print("Cancel button tapped");
}
alertController.addAction(cancelAction)
// Present Dialog message
self.present(alertController, animated: true, completion:nil)
}