0

I trying to retrieve JSON values from URL using below code, I am facing error of reading these values, also I checked the validity of JSON format and it is valid. also, I tried the url using postman and it is working fine.

let params = ["Xvalue":UserDefaults.standard.string(forKey: "com_id"), "Yvalue":UserDefaults.standard.string(forKey: "CID")] as! Dictionary<String, String>
print (params)
var request = URLRequest(url: URL(string: "http://x.x.x/index.php/GetJson")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")


let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>

        if (json["error"] != nil){
            self.hud.dismiss(afterDelay: 3.0)
            print(json["error"]!)
        }
        else if ((json["Code"]?.isEqual("0"))!){


            self.hud.dismiss(afterDelay: 3.0)

        }else{
            self.hud.dismiss(afterDelay: 3.0)
        }


      } catch {
        self.hud.dismiss(afterDelay: 3.0)
        print("Error info: \(error)")
    }
})


task.resume()

Error description :

Error info: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}

JSON Value:

JSON FORMAT

update : I found the issue and explained the answer : https://stackoverflow.com/a/55856132/1484193

Ali Alzahrani
  • 529
  • 1
  • 6
  • 29
  • There are other questions and answers that relate to the "Garbage at end" error. Have you read any and tried any solutions? – Gary Kerr Apr 24 '19 at 18:10
  • I expect that what you've posed in CodeBeautify is not exactly, byte-for-byte, what you're receiving from the server. I expect that what you're receiving from the server has some kind of extra garbage data at the end. Without showing the exact data you receive, it's not clear how we can help. – Rob Napier Apr 24 '19 at 18:17
  • 1
    I would start by printing out `String(data: data, encoding: .utf8)` and see what the actual data is. – Rob Napier Apr 24 '19 at 18:18

0 Answers0