I'm trying to add annotations on a MapKitView from a JSON file. Here's my code :
// 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
}
}
This code is executed. Then it goes to :
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()
}
}
The error is on the line if let latitude = Double(json[4] as! String)
I cant figured out why it's not working, i'm following this tutorial but I know I miss something... I hope someone can help me !
My JSON struct file :
[{
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...
}]
Thanks.
This line
crashes because
json
is an array of dictionaries and you want to force cast the dictionary to string , for old way you may needBut the correct way is using
Codable