当使用谷歌方向Api并在json中获取数据获取nil数据时

时间:2015-06-09 13:45:12

标签: ios json swift google-maps

我是swift编程和ios开发的新手。我试图在两个地点之间绘制路线,并遇到了这个问题。

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>

我收到错误:

  

致命错误:在解包可选值时意外发现nil

我尝试打印我收到的数据,结果为零

let baseURLDirections = "https://maps.googleapis.com/maps/api/directios/json?"

2 个答案:

答案 0 :(得分:0)

您未在请求网址中加入API key

您可以使用NSURLSession执行Directions API请求。当您从API响应中获取数据时,可以使用NSJSONSerialization.JSONObjectWithData()来解析JSON日期。

 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()
    }

如果您需要更新mapViewUITableView,可以在dispatch_async(dispatch_get_main_queue())关闭内执行该操作。

答案 1 :(得分:0)

您未在所请求的Serverkey非API密钥中添加URL ...创建一个服务器密钥并等待大约10分钟激活。