gpt4 book ai didi

ios - 使用 google Direction Api 并请求 json 中的数据时获取 nil 数据

转载 作者:行者123 更新时间:2023-11-30 14:18:58 26 4
gpt4 key购买 nike

我是 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>

我收到错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

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

最佳答案

您没有在请求网址中包含 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()) 闭包内执行此操作。

关于ios - 使用 google Direction Api 并请求 json 中的数据时获取 nil 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com