【问题标题】:Not getting full response in swift HTTP request?在快速的 HTTP 请求中没有得到完整的响应?
【发布时间】:2017-05-02 05:43:56
【问题描述】:

我正在使用谷歌路线 API。当我发送请求时,我得到了一半的响应。 这是我的代码:

func getDirections(_ origin: String!, destination: String!, completionHandler: @escaping ((_ status: String, _ success: Bool) -> Void)) {
        if let originLocation = origin {
            if let destinationLocation = destination {
                //var directionsURLString = baseURLDirections + "origin=" + "\(6.935299),\(79.880783)" + "&destination=" + "\(6.909411),\(79.894254)" + "&mode=driving"
                var directionsURLString = "https://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&key=YOUR_API_KEY"

                directionsURLString = directionsURLString.addingPercentEscapes(using: String.Encoding.utf8)!

                let directionsURL = URL(string: directionsURLString)

                DispatchQueue.main.async(execute: { () -> Void in
                    let directionsData = try? Data(contentsOf: directionsURL!)

                    var error: NSError?
                    NSLog("json: \(JSON(directionsData!))")



                })
            }
            else {
                NSLog("dest nil:")
                completionHandler("Destination is nil.", false)
            }
        }
        else {
            NSLog("Origin nil:")
            completionHandler("Origin is nil", false)
        }
    }

我得到的回应如下:

"routes" : [
    {
      "bounds" : {
        "northeast" : {
          "lat" : 41.8781139,
          "lng" : -87.6297872
        },
        "southwest" : {
          "lat" : 34.0523559,
          "lng" : -118.2435736
        }
      },
      "summary" : "I-55 S and I-44",
      "warnings" : [

      ],
      "copyrights" : "Map data ©2017 Google, INEGI",
      "waypoint_order" : [
        0,
        1
      ],
      "legs" : [
        {
          "via_waypoint" : [

          ],
          "distance" : {
            "value" : 932596,
            "text" : "579 mi"
          },
          "start_location" : {
            "lat" : 41.8781139,
            "lng" : -87.6297872
          },
          "traffic_speed_entry" : [

          ],
          "start_address" : "Chicago, IL, USA",
          "end_address" : "Joplin, MO, USA",
          "end_location" : {
            "lat" : 37.0842313,
            "lng" : -94.51348499999999
          },
          "duration" : {
            "value" : 30893,

一半没有在控制台打印。这是什么原因??

【问题讨论】:

  • 只是没有打印还是您没有收到?尝试在打印位置设置断点并在检查器中查看变量而不是打印它。
  • 你得到了完整的回应,还不是一半。 print() 方法有时无法在控制台上正确打印长 JSON 数据。为了确认您可以在调试窗口中调试它。
  • 是的,最初我打印状态,即使上面没有显示,它也会打印一个值 OK。但我试图打印为空的“way_pointArray”。
  • 我把我的答案放在下面请检查我希望它对你有帮助我得到了整个回复

标签: swift google-places-api google-maps-sdk-ios google-directions-api


【解决方案1】:

这样试试吧!

var session = URLSession()
override init() {
    let configuration = URLSessionConfiguration.default
    session = URLSession(configuration: configuration)
}

func getDirections(_ origin: String!, destination: String!, completionHandler: @escaping ((_ status: String, _ success: Bool) -> Void)) {

    var directionsURLString = "https://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&key=YOUR_API_KEY"
    directionsURLString = directionsURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    let weatherRequestUrl = URL(string: directionsURLString)
    let request = NSMutableURLRequest(url: weatherRequestUrl!)
    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

        guard error == nil && data != nil else {

            completionHandler("Your message here",false)
            return
        }
        if let httpStatus = response as? HTTPURLResponse{
            if httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
        }
        do {
            let dataDictionary = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as! NSDictionary

            print("Response dictionary is:\(dataDictionary)")
            completionHandler("your message here",false)
        }
        catch let error as NSError {
            print("Error = \(error.localizedDescription)")
            completionHandler("Your message here",false)
        }
    }
    task.resume()
}

【讨论】:

  • @Anushka Madushan 如果答案是完美的工作请投票,所以这对其他用户也很有用。
猜你喜欢
  • 2016-07-10
  • 1970-01-01
  • 2015-06-20
  • 2012-04-23
  • 2017-04-04
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 2020-07-06
相关资源
最近更新 更多