mapView.addAnnotation() 在触摸地图之前不向地图添加图钉

mapView.addAnnotation() Not Adding Pins to Map until touching map

我有一个故事板的 mapView,一切正常,除了一件事:我从 RESTful 调用中添加并添加到地图 mapView.addAnnotation() 的注释没有显示在直到我触摸并移动地图。这是相关代码:

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()

    }
  }

问题是您正在从后台线程更新 UI。您添加注释的块是由于 dataTask 完成而发生的,并且这是在后台发生的。将注释代码包装在 DispatchQueue.main.async { } 块中,您应该会看到注释显示正常。

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)
}