Я искал эту тему и нашел несколько кодов, которые пытался внедрить в свой проект, но это не сработает!
Итак, чего я хочу достичь?
Я хочу иметь кнопку в пользовательском интерфейсе, и когда пользователь нажимает кнопку, приложение отображает направления к определенной точке в GoogleMap. Но моя функция падает на URL.
Это мой код:
func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(src)&destination=\(dst)&sensor=false&mode=driving&key=**API_KEY**" <- // Here I place API-Key
let url = URL(string: urlString) // Here is the crash!
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
let routes = json["routes"] as! NSArray
self.mapView.clear()
OperationQueue.main.addOperation({
for route in routes
{
let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
let points = routeOverviewPolyline.object(forKey: "points")
let path = GMSPath.init(fromEncodedPath: points! as! String)
let polyline = GMSPolyline.init(path: path)
polyline.strokeWidth = 3
let bounds = GMSCoordinateBounds(path: path!)
self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))
polyline.map = self.mapView
}
})
}catch let error as NSError{
print("error:\(error)")
}
}
}).resume()
}
Я не знаю, может ли быть проблема с API-ключом или есть что-то еще. Я читал, что пробелы и т.д. могут вызвать эту проблему, но я не могу найти, что не так!
Сообщение об ошибке:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
2019-06-14 16:50:45 Fatal error: Unexpectedly found nil while unwrapping an Optional value