I've a view with a map inside. I'd like to achieve the following: when the user taps on the map an annotation is displayed and selected (so the callout bubble is shown) until the user taps another point on the map (in this case, the previous annotation should be removed).
The problem is that when I tap on the map the annotation is added and selected for a little time, then somehow it's deselected (so the callout disappears). I want the callout bubble to persist until the user taps on another point
In the following there is my attempt, could anyone help me, please?
@objc func handleTap(_ sender: UITapGestureRecognizer){
//...some code that computes the country code starting from latitude and longitude
var countryCurrency = ""
func countryRequest(countryLabel: String, completion: @escaping (String)->()){
//api request that receives the currency name of the country
completion(countryCurrency)
}
countryRequest(countryLabel: countryLabel){ countryCurrency in
DispatchQueue.main.async {
let locat:CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationCoord.latitude, locationCoord.longitude)
let annotation = MKPointAnnotation()
annotation.coordinate = locat
annotation.title = countryCurrency
annotation.subtitle = "subtitle"
self.mapView.addAnnotation(annotation)
self.mapView.selectAnnotation(annotation, animated: true)
}
}
}
I also have an extension of the MKMapViewDelegate to customise the callout:
extension MapsItem: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is MKPointAnnotation){
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "demo")
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "demo")
annotationView!.canShowCallout = true
annotationView!.sizeToFit()
}
else{
annotationView!.annotation = annotation
}
return annotationView
}
}
Thanks in advance!!
Try this
set isTappingNow to true before adding annotation and to false after selecting it
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView)
{
if(!isTappingNow)
{
self.mapView.selectAnnotation(view.annotation, animated: false)
}
}