2016-12-01 16 views
0

我加載一些地理數據從我的服務器,並希望顯示他們扔註釋:更新註解裝載HTTP

Alamofire.request("http://localhost:1234/app/data").responseJSON { response in 
    switch response.result { 
    case .success(let value): 
     let json = JSON(value) 
     var annotations = [Station]() 
     for (key, subJson):(String, JSON) in json { 
      let lat: CLLocationDegrees = subJson["latitude"].double! as CLLocationDegrees 
      let long: CLLocationDegrees = subJson["longtitude"].double! as CLLocationDegrees 
      self.annotations += [Station(name: "test", lat: lat, long: long)] 
     } 

     DispatchQueue.main.async { 
      let allAnnotations = self.mapView.annotations 
      self.mapView.removeAnnotations(allAnnotations) 
      self.mapView.addAnnotations(annotations) 
     } 

    case .failure(let error): 
     print(error) 
    } 
} 

和我Station類:

class Station: NSObject, MKAnnotation { 
    var identifier = "test" 
    var title: String? 
    var coordinate: CLLocationCoordinate2D 

    init(name:String, lat:CLLocationDegrees, long:CLLocationDegrees) { 
     title = name 
     coordinate = CLLocationCoordinate2DMake(lat, long) 
    } 
} 

所以我做什麼,基本上是:

加載來自遠程服務的數據並在MKMapView上顯示這些數據作爲註釋。

但是:不知何故,這些註釋並未加載到地圖上,即使我先「刪除」,然後再「添加」它們。

有什麼建議嗎?

+0

當你設置你的反應中斷點,按預期打印所有JSON值?它是否按照您期望的順序擊中了該方法的每個部分? –

回答

0

您正在將Station實例添加到某個self.annotations屬性,而不是您的本地變量annotations。因此,annotations local var仍然只是那個空數組。

顯然,你可以修復,通過引用annotations而不是self.annotations

var annotations = [Station]() 
for (key, subJson): (String, JSON) in json { 
    let lat = ... 
    let long = ... 
    annotations += [Station(name: "test", lat: lat, long: long)] // not `self.annotations` 
} 

或者你可以使用map,完全避免這種潛在的混亂:

let annotations = json.map { key, subJson -> Station in 
    Station(name: "test", lat: subJson["latitude"].double!, long: subJson["longitude"].double!) 
}