当使用谷歌方向Api和请求数据在JSON获取零数据

我是新手,编程和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> 

我收到错误:

致命错误:意外地发现零,而解包一个可选值

我试图打印我收到的数据,它出来零

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

您没有在请求url中包含API key

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

  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())闭包内完成。

您没有将Serverkey包含在请求的URL Not API键中…创build一个服务器密钥并等待大约10分钟以激活。