Getting NSDebugDescription=字符0周围的值无效.在Swift中使用PHP发布请求时



当我试图用swift通过php发布数据时,遇到了一个错误,上面写着Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

这个错误是什么意思?我用swift解决了与使用PHP相关的其他问题,但我仍然收到这个错误。

如何修复此错误?

这是我的代码:

let ADD_PROP_URL = "https://example.com/WebService/api/addProperty.php"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

@IBAction func addProperty(_ sender: Any) {

let requestURL = NSURL(string: ADD_PROP_URL)

var request = URLRequest(url: requestURL! as URL)

request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let propName = propName.text
let propPrice = propPrice.text
let propBed = propBedrooms.text
let propLoc = propLoc.text

let postParameters = "name="+propName!+"&price="+propPrice!+"&bedrooms="+propBed!+"&location="+propLoc!;

request.httpBody = postParameters.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request){
data, response, error in

if error != nil{
print("error is (error)")
return;
}

do {

let myJSON =  try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

if let parseJSON = myJSON {
var msg : String!
msg = parseJSON["message"] as! String?
print(msg)
print(response)
print(data)
}
} catch {
print(error)
print(response)
print(data)
}

}

task.resume()

}

你能试一下下面的代码,告诉我们你得到了什么吗:

@IBAction func addProperty(_ sender: Any) {
if let requestURL = URL(string: ADD_PROP_URL) {
var request = URLRequest(url: requestURL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

var components = URLComponents(url: requestURL, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "name", value: propName.text ?? ""),
URLQueryItem(name: "price", value: propPrice.text ?? "") ,
URLQueryItem(name: "bedrooms", value: propBedrooms.text ?? "") ,
URLQueryItem(name: "location", value: propLoc.text ?? "") ]

if let query = components.url!.query {
request.httpBody = Data(query.utf8)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
print("error is (error)")
return
}
if let data = data {
print("the data: (String(data: data, encoding: .utf8))")
}
}
task.resume()
} else {
print("bad URL: (ADD_PROP_URL)")
}
}

最新更新