Search code examples
swiftgoogle-places-apigoogle-maps-sdk-iosgoogle-directions-api

Not getting full response in swift HTTP request?


I'm using google directions API. When i send the request i'm getting half of the response. This is my code:

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)
        }
    }

Response that i'm getting is below:

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

Half of it is not printing on the console.What's the reason for that??


Solution

  • Try like this!

    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()
    }