线程1:Swift 3中的EXC_BAD_INSTRUCTION

时间:2016-10-20 20:27:59

标签: ios json uitableview google-maps swift3

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        // 1
        self.dismiss(animated: true, completion: nil)
        // 2
        let correctedAddress:String! = self.searchResults[(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
        let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false")


     let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in

            // 3
            do {
                if let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any],
                    let results = jsonObject["results"] as? [[String:Any]], !results.isEmpty,
                    let geometry = results[0]["geometry"] as? [String:Any],
                    let location = geometry["location"] as? [String:Double],
                    let lat = location["lat"], let lng = location["lng"] {

                    print("lat: \(lat) - lng: \(lng)")
                }




            }catch {
                print("Error")
            }
        })
        // 5
        task.resume()
    }

图像显示我在运行应用程序并搜索某个位置并单击它以在地图上显示后收到的错误。

enter image description here

2 个答案:

答案 0 :(得分:0)

似乎您的网址正在创建崩溃。展开后,您的网址可能是零。如果适用于您,请尝试使用以下代码

let valueAtIndex = self.searchResults![(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
guard let correctedAddress = valueAtIndex else { return }
let adrString:String = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false"
let url:URL = URL(string: adrString)!

答案 1 :(得分:0)

如果仍有问题,您可以尝试将addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)替换为addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

我不确定您的查询中是否有特定字符被拒绝,但我遇到的问题与您的问题类似,urlQueryAllowedurlPathAllowed字符集合正是为了避免这种问题