我从情节提要中获得了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()
}
}
答案 0 :(得分:1)
问题是您正在从后台线程更新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)
}