当使用谷歌方向Api和请求数据在json获取零数据 [英] when using google directions Api and requesting data in json getting nil data

查看:119
本文介绍了当使用谷歌方向Api和请求数据在json获取零数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对swift编程和ios开发很陌生。

  func getDirections(origin:String!,destination: String !, waypoints:Array< String>!,travelMode:AnyObject !, completionHandler :((status:String,success:Bool) - > Void)){
如果let originLocation = origin {
if let destinationLocation = destination {
var directionsURLString = baseURLDirections +origin =+ originLocation +& destination =+ destinationLocation

directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

让directionsURL = NSURL(字符串:directionsURLString)
$ b $ dispatch_async(dispatch_get_main_queue(),{() - >无效
let directionsData = NSData(contentsOfURL: )

println(directionsData)

var error:NSError?
让词典:Dictionary< NSObject,AnyObject> = NSJSONSerialization.JSONObjectWithData(directionsData !, options :NSJSONReadingOptions.MutableContainers,error:& error)as!Dictionary< NSObject,AnyObject>

我是出现错误:
$ b


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

我尝试打印我收到的数据,并且它出来nil

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


API键。



您可以使用 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,选项:nil,error:nil)as!NSDictionary
println(object)

let routes = object [routes] as![NSDictionary]
路由中的路由{
println(r oute [summary])
}
dispatch_async(dispatch_get_main_queue()){
//更新您的用户界面
}
}
else {
println(方向API错误)
}

})。resume()
}

如果您需要更新您的 mapView UITableView 您可以在 dispatch_async(dispatch_get_main_queue())闭包内完成。


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

解决方案

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.

这篇关于当使用谷歌方向Api和请求数据在json获取零数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆