Reputation: 14
I have a mapView from storyboard and everything works, except for one thing: the annotations I make from a RESTful call and add to the map mapView.addAnnotation() don't show up on the map until I touch and move the map. Here's the relevant code:
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
// API Call
URLSession.shared.dataTask(with: mRequest) {
(data, response, error) in do {
let data = data
...
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(lat!, lon!)
annotation.title = name as? String
annotation.subtitle = details as? String
self.mapView.addAnnotation(annotation)
}
...
}.resume()
}
}
Upvotes: 0
Views: 246
Reputation: 2578
The issue is that you're updating the UI from a background thread. The block where you are adding the annotations is occurring as a result of the dataTask completing, and this is happening in the background. Wrap you annotation code in a DispatchQueue.main.async { }
block and you should see the annotations show up fine.
DispatchQueue.main.async{
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(lat!, lon!)
annotation.title = name as? String
annotation.subtitle = details as? String
self.mapView.addAnnotation(annotation)
}
Upvotes: 1