在Google Maps iOS SDK中获取两点之间的路线

时间:2018-07-06 16:22:17

标签: ios swift google-maps nsurlsession

我有以下代码来获取Google Maps iOS SDK中两点之间的路径。但是,我什至没有收到任何数据甚至任何错误。

let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(latitude),\(longitude)&destination=\(finallat),\(finallong)&key=**************")
URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
    if let data = data {
        do {
            // Convert the data to JSON
            let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

            if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] {
                print(url)
                print(explanation)
            }
        }  catch let error as NSError {
            print(error.localizedDescription)
        }
    } else if let error = error {
        print(error.localizedDescription)
    }
}

1 个答案:

答案 0 :(得分:2)

您不会对dataTask做任何事情,因此实际上并没有调用它。您需要致电resume()

let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(latitude),\(longitude)&destination=\(finallat),\(finallong)&key=**************")
let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in
    if let data = data {
        do {
            // Convert the data to JSON
            let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

            if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] {
                print(url)
                print(explanation)
            }
        }  catch let error as NSError {
            print(error.localizedDescription)
        }
    } else if let error = error {
        print(error.localizedDescription)
    }
}
task.resume()