when using google directions Api and requesting data in json getting nil data

1.1k Views Asked by At

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?"
2

There are 2 best solutions below

1
On BEST ANSWER

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 use NSJSONSerialization.JSONObjectWithData() to parse the JSON date.

 func directionAPITest() {

        let directionURL = "https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY"
        let request = NSURLRequest(URL: NSURL(string:directionURL)!)
        let session = NSURLSession.sharedSession()
        session.dataTaskWithRequest(request,
            completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in

                if error == nil {
                    let object = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
                    println(object)

                    let routes = object["routes"] as! [NSDictionary]
                    for route in routes {
                        println(route["summary"])
                    }
                    dispatch_async(dispatch_get_main_queue()) {
                      //update your UI here 
                    }
                }
                else {
                    println("Direction API error")
                }

        }).resume()
    }

If you need to udpate your mapView or UITableView you can do that inside the dispatch_async(dispatch_get_main_queue()) closure.

0
On

You didnt include the Serverkey in your requested URL Not API key...Create one server key and wait for about 10 minutes to activate.