У меня есть MapView
, где вы можете добавить или удалить MKAnnotation
через Firebase. Когда вы добавляете новое оповещение, оно публикуется в Firebase, на котором у меня есть наблюдатели как для добавленных, так и для удаленных снимков.
Firebase корректно обновляется, карта корректно обновляется для добавленных снимков, но не обновляется для удаленныхиз них. В обеих функциях я проверяю, что массивы, в которых я сохраняю предупреждения, корректно обновляются до и после получения снимков, и они действительно являются правильными.
Таким образом, единственное, что не происходит, - это значок, удаленный с карты ... когдаЯ использую self.mapView.removeAnnotation(annotationToRemove)
, который я определяю на основе входящего снимка. Если я вместо этого удаляю все аннотации и заново добавляю их из массива, это работает правильно. Просто ужасно видеть эту постоянно обновляющуюся карту ... это больше похоже на ошибку, чем на обновление карты. Вы видите, почему удаление определенного не работает ?? Как всегда большое спасибо. Это код:
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)
})
}