Refresh IOS Swift 3 map

0

Good morning.

I'm making an application that shows a map, and receives from a webservice an array with JSOn opbjects, which contain coordinate data, and then add PINs to the map, showing the location of the users.

The connection works correctly and the data is received without problems, but the map does not refresh, it does not show the PINS, until the user of the App does something with the map (zoom, move the map ...) .

Is there a way to force the map refresh, once all the data is received?

I attach the code of the method to update the data (which is called by pressing a button on the interface).

@IBAction func UPDATE (_ sender: Any) {

     let url = URL(string: "http://mi_url.es")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if error != nil{

            print("ERROR")

        }else{

            if let content = data{

            do{

                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject


                if let taxis = myJson["taxis"] as? NSArray {                 
                    if let hashTags = myJson["taxis"] as? [[String:String]] {
       self.mapView.removeAnnotations(self.mapView.annotations)

                        for tag in hashTags {

                            let laLongitud:String = tag["longitud"]!
                            let laLatitud:String = tag["latitud"]!

                            self.pintaTaxistas(latitud: laLatitud, longitud: laLongitud)
                         }
                    }

            }else {
                    print("No puedo pintar el array")
                }

                }catch{

                }
            }
        }
    }
     task.resume()

}

func pintaTaxistas (latitude: String, length: String) {

   let lat = Double(latitud) ?? 0.0
   let long = Double(longitud) ?? 0.0
        let annotation = MKPointAnnotation()
        annotation.title = "Taxi"
        annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

        mapView.addAnnotation(annotation)        
}

Greetings and thanks in advance.

    
asked by Pifia 05.04.2017 в 19:44
source

1 answer

2

If I'm not wrong, the closure in URLSession.shared.dataTask(with: url) { (data, response, error) in

leaves you in a background queue ... So to be able to paint in the UI you will need to return to mainQueue .

Try this:

func pintaTaxistas (latitud:String, longitud:String) {

   let lat = Double(latitud) ?? 0.0
   let long = Double(longitud) ?? 0.0
   let annotation = MKPointAnnotation()
   annotation.title = "Taxi"
   annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)

   DispatchQueue.main.async {
       self.mapView.addAnnotation(annotation)
   }
}
    
answered by 06.04.2017 / 13:11
source