Vincenzo
Vincenzo

Reputation: 6358

MapView doesn't update view after removing MKAnnotation Swift4

I have a MapView where you can add or delete MKAnnotation via Firebase . When you add a new alert it get posted to Firebase on which I have observers both for added and removed snapshots.

Firebase gets updated correctly, map gets updated correctly for added snapshots, but doesn't get updated for deleted ones. I check in both functions that the arrays where I save the alerts are correctly updated before and after receiving the snapshots and they indeed are correct.

So the only thing not happening is the icon removed from the map.. when I use self.mapView.removeAnnotation(annotationToRemove)which I define based on the incoming snapshot. If I instead remove all the annotations and re add them from the array it works correctly.It's just horrible to see this continuously updating map.. seems more like a glitching error then an updating map. Can you see why removing the specific one doesn't work?? As always thank you very much. This is the code:

func getAlerts(setCompletion: @escaping (Bool) -> ()) {

//        self.mapView.removeAnnotations(mapView.annotations)
//        MapArray.alertNotificationCoordinatesArray.removeAll()
//        MapArray.userAlertNotificationArray.removeAll()

        print("  MapArray.alertNotificationCoordinatesArray before getAlerts is: \(MapArray.alertNotificationCoordinatesArray)")
        print(" MapArray.userAlertNotificationArray before getAlerts is: \(MapArray.userAlertNotificationArray)")

        ref = Database.database().reference()
        //        ref?.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Community").child("Alert Notifications").observe(.childAdded, with: { (snapshot) in

        ref?.child("Continent").child("Europe").child("Country").child("\(String(describing: userDetails.country!))").child("Region").child("\(String(describing: userDetails.region!))").child("City").child("\(String(describing: userDetails.city!))").child("Community").child("Alert Notifications").observe(DataEventType.childAdded, with: { (snapshot) in
//            self.mapView.removeAnnotations(self.mapView.annotations) // wrong!! causes all annotations to be deleted when any new one is  notified by anyone
//            print(" added snapshot is: \(snapshot)")
            guard let data = snapshot.value as? [String:String] else { return }

            //            guard let firebaseKey = snapshot.key as? String else { return }
            let firebaseKey = snapshot.key
            let dataLatitude = data["Latitude"]!
            let dataLongitude = data["Longitude"]!
            let type = data["Description"]!
            //            let id = Int(data["Id"]!)
            let id = data["Id"]!
            let userName = data["user"]!
            let alertImageUrl = data["alertImageUrl"] ?? ""
            let alertImageName = data["alertImageName"] ?? ""
            let doubledLatitude = Double(dataLatitude)
            let doubledLongitude = Double(dataLongitude)
            let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

            let userAlertAnnotation = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: firebaseKey, title: type, id: id, userName: userName, alertImageUrl: alertImageUrl, alertImageName: alertImageName)
            MapArray.userAlertNotificationArray.append(userAlertAnnotation)  // array of notifications coming from Firebase
            MapArray.alertNotificationCoordinatesArray.append(recombinedCoordinate) // array for checkig alerts on route
            print("  MapArray.alertNotificationCoordinatesArray after getNewerAlerts is: \(MapArray.alertNotificationCoordinatesArray)")
            print("   MapArray.userAlertNotificationArray after getNewerAlerts is: \(MapArray.userAlertNotificationArray)")
            self.mapView.addAnnotation(userAlertAnnotation)
            setCompletion(true)
//            self.mapView.addAnnotations(MapArray.userAlertNotificationArray)
        })
    }



func getDeletedAlerts(setCompletion: @escaping (Bool) -> ()) {

        ref?.child("Continent").child("Europe").child("Country").child("\(String(describing: userDetails.country!))").child("Region").child("\(String(describing: userDetails.region!))").child("City").child("\(String(describing: userDetails.city!))").child("Community").child("Alert Notifications").observe(DataEventType.childRemoved, with: { (snapshot) in

            print("    MapArray.userAlertNotificationArray before getDeletedAlerts snapshot is: \(MapArray.userAlertNotificationArray)")
            print("    MapArray.alertNotificationCoordinatesArray before getDeletedAlerts snapshot is: \(MapArray.alertNotificationCoordinatesArray)")

            print("        removed snapshot is: \(snapshot)")
            guard let data = snapshot.value as? [String:String] else { return }
            let firebaseKey = snapshot.key
            let dataLatitude = data["Latitude"]!
            let dataLongitude = data["Longitude"]!

            let type = data["Description"]!
//            let id = Int(data["Id"]!)
            let id = data["Id"]!
            let userName = data["user"]!
            let alertImageUrl = data["alertImageUrl"] ?? ""
            let alertImageName = data["alertImageName"] ?? ""
            let doubledLatitude = Double(dataLatitude)
            let doubledLongitude = Double(dataLongitude)
            let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)


            let annotationToRemove = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: firebaseKey, title: type, id: id, userName: userName, alertImageUrl: alertImageUrl, alertImageName: alertImageName)

            MapArray.userAlertNotificationArray.removeAll(where: { ($0.firebaseKey == firebaseKey) }) //remove the alert
            MapArray.alertNotificationCoordinatesArray.removeAll(where: { ($0.latitude == recombinedCoordinate.latitude && $0.longitude == recombinedCoordinate.longitude) })

            self.mapView.removeAnnotation(annotationToRemove)
//            self.mapView.removeAnnotations(self.mapView.annotations)
//            self.mapView.addAnnotations(MapArray.userAlertNotificationArray)

            print("    MapArray.userAlertNotificationArray after getDeletedAlerts snapshot is: \(MapArray.userAlertNotificationArray)")
            print("    MapArray.alertNotificationCoordinatesArray after getDeletedAlerts snapshot is: \(MapArray.alertNotificationCoordinatesArray)")
            setCompletion(true)
        })
    }

Upvotes: 2

Views: 252

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You create the annotation and try to remove it which for sure not added to the mapView

let annotationToRemove = UserAlert( 
self.mapView.removeAnnotation(annotationToRemove)

While you should do

for item in  self.mapView.annoations {
   if let ann = item as? UserAlert , ann.id == annotationToRemove.id {
       self.mapView.removeAnnotation(ann)
   }
}

Upvotes: 1

Related Questions