gpt4 book ai didi

swift - 更新用http加载的注释

转载 作者:行者123 更新时间:2023-11-30 12:51:20 25 4
gpt4 key购买 nike

我正在从我的服务器加载一些地理数据并希望显示它们并抛出注释:

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

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 上。

但是:不知何故,这些注释没有加载到 map 上,即使我先“删除”然后再“添加”它们。

有什么建议吗?

最佳答案

您要将 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!)
}

关于swift - 更新用http加载的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40914627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com