I am new to programming and ios development with swift. I am trying to map a route between two locations and have encountered this problem.
func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, travelMode: AnyObject!, completionHandler: ((status: String, success: Bool) -> Void)) {
if let originLocation = origin {
if let destinationLocation = destination {
var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation
directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let directionsURL = NSURL(string: directionsURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let directionsData = NSData(contentsOfURL: directionsURL!)
println(directionsData)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary<NSObject, AnyObject>
I am getting the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I tried printing the data which I was receiving and it comes out nil
let baseURLDirections = "https://maps.googleapis.com/maps/api/directios/json?"
You didnt include the
API key
in your request URL.You can use
NSURLSession
to do the Directions API request. When you get the data back from API response, you can useNSJSONSerialization.JSONObjectWithData()
to parse the JSON date.If you need to udpate your
mapView
orUITableView
you can do that inside thedispatch_async(dispatch_get_main_queue())
closure.