我是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
我试着打印我收到的数据,结果是nil
let baseURLDirections = "https://maps.googleapis.com/maps/api/directios/json?"
您的请求URL中没有包含API key
。
您可以使用NSURLSession
来执行指示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()
}
如果你需要更新你的mapView
或UITableView
,你可以在dispatch_async(dispatch_get_main_queue())
闭包内完成。
您没有在您请求的URL
Not API key中包含Serverkey
…创建一个服务器密钥并等待大约10分钟来激活。