我尝试使用下面的代码从URL检索JSON值,我遇到读取这些值的错误,而且我检查了JSON格式的有效性,并且它是有效的。 另外,我使用邮递员尝试了该网址,并且工作正常。
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()
错误说明:
错误信息:错误域= NSCocoaErrorDomain代码= 3840“垃圾结束。” UserInfo = {NSDebugDescription =垃圾。}
JSON值:
更新: 我发现了问题并解释了答案: https://stackoverflow.com/a/55856132/1484193