我有一个userAlertAnnotationArray: [MKAnnotations]
,它从Firebase检索的数据中获取条目。删除部分与Firebase中的帖子和数组中的条目完美配合,但是当从地图中删除所选的MKAnnotation时,它会失败。它将错误的注释从地图中删除。
如果我退出mapVC到menuVC并重新输入mapVC,那么正确的注释就消失了。
经过几次尝试,我注意到了它,因为仅当我重新输入mapVC时,我才得到超出范围的错误。我不想调用viewDiedLoad()函数来刷新视图,因为每次删除注释时,这将从Firebase读取每个条目。
您能看到我在哪里犯了编码错误吗?更新显示注释失败,userAlertAnnotationArray将注释删除。如果您需要查看更多代码或其他功能,请告诉我。提前致谢。这是didSelect函数:
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)
}
答案 0 :(得分:1)
问题在于您是从地图视图上的注释数组而不是数组中获取索引;它们可能有所不同,例如,如果地图显示的是另一个注释的用户位置。
尝试以此替换您的index
声明:
let index = (self.userAlertNotificationArray as NSArray).index(of: annotation)