json - 使用 JSON 文件在 MapKit 中添加 Swift 注释

标签 json swift mapkit mapkitannotation

我正在尝试通过 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...
}]

谢谢。

最佳答案

这一行

Double(json[4] as! String)

崩溃是因为 json 是一个字典数组,你想强制将字典转换为 string ,对于你可能需要的旧方法

var allCoor = [CLLocationCoordinate2D]()

init?(json: [Any]) { 

    if let content = json as? [[String:Any]] { 
       content.forEach {
          if let latitude = $0["EquGpsX"] as? String , let longitude = $0["EquGpsY"] as? String
             self.allCoor.append( CLLocationCoordinate2D(latitude:Double(latitude)!, longitude: Double(longitude)!))
          }
          else {
            ///// 
          } 
       }
    } 
}

但正确的方法是使用 Codable

关于json - 使用 JSON 文件在 MapKit 中添加 Swift 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309637/

相关文章:

php - 通过 JSON 数组/对象返回 MYSQL 查询结果?

iphone - 使用 NSJSONSerialization 将 NSMutableDictionary 转换为 JSON 返回不同的结果

swift - 创建框架和对成员 'log' 的模糊引用

swift - 收到 "unexpectedly found nil while unwrapping an Optional value"错误

ios - MKMapSnapshotter 从快照中删除 "Legal"

java - 如何通过 JDBC 使用包含问号 "?"的 PostgreSQL JSON(B) 运算符

javascript - 奇怪的行为 json_decode

ios - 如何检查用户是否在 firebase 的不同 View Controller 中登录

ios - XCode8 TextureAtlas编译器没有产生

当同一位置有多个项目时,iOS 更改标注