Swift Google Directions API JSON - EXC_BAD_INSTRUCTION (код =EXC_I386_INVOP, субкод =0x0)
Я пытаюсь получить данные о маршрутах с помощью Google API, но он продолжает падать. Вот мой код:
let baseURLDirections = "https://maps.googleapis.com/maps/api/directions/json?"
var selectedRoute: Dictionary<NSObject, AnyObject>!
var overviewPolyline: Dictionary<NSObject, AnyObject>!
var originCoordinate: CLLocationCoordinate2D!
var destinationCoordinate: CLLocationCoordinate2D!
var originAddress: String!
var destinationAddress: String!
func getDirections(origin: String, destination: String, waypoints: Array<String>!, travelMode: AnyObject!, completionHandler: ((status: String, success: Bool) -> Void)) {
var directionsURLString = baseURLDirections + "origin=" + origin + "&destination=" + destination
directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let directionsURL = NSURL(string: directionsURLString)
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: directionsURL!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
do {
let directionsData = NSData(contentsOfURL: directionsURL!)
if let dictionary: Dictionary<NSObject, AnyObject> = try NSJSONSerialization.JSONObjectWithData(directionsData!, options: .MutableContainers) as? Dictionary<NSObject, AnyObject> {
let status = dictionary["status"] as! String
if status == "OK" {
self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0]
self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>
let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>>
let startLocationDictionary = legs[0]["start_location"] as! Dictionary<NSObject, AnyObject>
self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double)
let endLocationDictionary = legs[legs.count - 1]["end_location"]as! Dictionary<NSObject, AnyObject>
self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double)
self.originAddress = legs[0]["start_address"]as! String
self.destinationAddress = legs[legs.count - 1]["end_address"]as! String
self.calculateTotalDistanceAndDuration()
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
} catch let error as NSError {
print(error)
completionHandler(status: "", success: false)
}
}
task.resume()
}
Он говорит "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" в
self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>
и даже когда я удаляю весь код внутри
if let dictionary: Dictionary<NSObject, AnyObject> = try NSJSONSerialization.JSONObjectWithData(directionsData!, options: .MutableContainers) as? Dictionary<NSObject, AnyObject> {
Я получаю EXC_BAD_INSTRUCTION (код = EXC_I386_INVOP, субкод =0x0). Как мне это решить?
2 ответа
Решение
Это сработало, когда я изменился
directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.UR>LHostAllowedCharacterSet())!
в
directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!
Спасибо, что указал мне правильное направление! В Swift 3.0 это означает:
SearchString = SearchString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
Вот еще один полезный модификатор строки для подготовки URL (удаляет акценты и так далее, но не такие странные символы, как "ø"):
SearchString = SearchString.folding(options: .diacriticInsensitive, locale: .current)
Это сработало, когда я изменился
directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
в
directionsURLString = directionsURLString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!