Swift:JSONSerialization SIGABRT 错误

Swift:JSONSerialization SIGABRT error

我收到 JSONSerialization 的 SIGABR 错误...这是代码(XCode8)

func makeHTTPPostRequest(path: String, body: String, onCompletion: @escaping ServiceResponse) {
    var err: NSError?
    let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)

    // Set the method to POST
    request.httpMethod = "POST"

    // Set the POST body for the request

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])

    let session = URLSession.shared

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        let json:JSON = JSON(data: data!)
        onCompletion(json, err)
    })
    task.resume()
}

这里是 body 变量的值:{"firstName":"adds","email":"asd","lastName":"add", "password":"asdas"}

任何帮助将不胜感激!

您需要将语法更新为 swift 3.0

let dataTsked = session.dataTask(with: URL(string: path)!) { (data, response, error) in
    if (error != nil) {

body 不是 JSONObject,而是 String 的一种。您尝试使用的函数需要一个顶级基础对象,例如 DictionaryArray.

您只需将正文数据传递给请求即可。

所以代替:

request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])

应该是:

request.httpBody = body.data(using: .utf8)!

注意:正文需要格式正确 JSON 字符串