【发布时间】:2018-11-14 22:24:13
【问题描述】:
我正在尝试通过 JSON 文件在 MapKitView 上添加注释。 这是我的代码:
// On récupère les valeurs JSON
func loadInitialData() {
if let path = Bundle.main.path(forResource: "Playgrounds", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
print(jsonResult)
let jsonResultAs = jsonResult as? Dictionary<String, AnyObject>
print(jsonResultAs!)
let playground = jsonResultAs!["playgrounds"] as? [Any]
print(playground!)
// 5
let validWorks = playground.flatMap { Playground(json: $0) }
playgrounds.append(validWorks!)
} catch {
// handle error
}
}
此代码已执行。然后转到:
init?(json: [Any]) {
// json[16] = on prend le 16ème paramètre de la réponse json. Pour le titre, s'il est null, on en met un par défaut
self.title = json[6] as? String ?? "Aucun nom"
//self.locationName = json[3] as! [String]()
self.locationName = json[2] as? String ?? "Lieu non défini"
//self.discipline = json[2] as! String
self.discipline = ""
// On récupère latitude et longitude en string puis on convertit en double
if let latitude = Double(json[4] as! String),
let longitude = Double(json[5] as! String) {
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
} else {
self.coordinate = CLLocationCoordinate2D()
}
}
错误在线if let latitude = Double(json[4] as! String)
我不知道为什么它不起作用,我正在关注this tutorial,但我知道我错过了一些东西......我希望有人能帮助我!
我的 JSON 结构文件:
[{
ComLib = Ambronay;
DepCode = 1;
DepLib = Ain;
EquEclairage = "-1";
EquGpsX = "5.3625";
EquGpsY = "46.0075";
InsNom = "Terrain de basket";
NatureLibelle = Decouvert;
NatureSolLib = Sable;
}, {
ComLib = Ambutrix;
DepCode = 1;
DepLib = Ain;
EquEclairage = "-1";
EquGpsX = "5.34";
EquGpsY = "45.93889";
InsNom = "Ecole Primaire";
NatureLibelle = Decouvert;
NatureSolLib = Bitume;
},
etc...
}]
谢谢。
【问题讨论】:
-
将 json 打包后发布,以便我们帮助您解码
标签: json swift mapkit mapkitannotation