我正在尝试使用Swift向一个带有一些JSON数据的php脚本发出POST请求。当我运行以下代码时,我的应用程序崩溃,并且没有信息记录到控制台。
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
let url = NSURL(string: "https://www.centrohq.com/api/payment/")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
print(response)
})
task.resume()
}
答案 0 :(得分:0)
我尝试展开网址。我过去曾经遇到过一些问题,只是不能安全地解开传入的网址:
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
if let url = NSURL(string: "https://www.centrohq.com/api/payment/") {
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
print(response)
})
task.resume()
}
}
答案 1 :(得分:0)
此代码不是错误的原因。另一段代码同时执行导致它失败。