Swift:JSONSerialization SIGABRT错误

时间:2016-10-08 01:55:12

标签: swift xcode sigabrt nsjsonserialization

我收到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”}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

JSONObject不是String,而是Dictionary的类型。您尝试使用的功能需要一个顶级的Foundation对象,如Arrayrequest.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])

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

所以而不是:

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

它应该是:

import React, { Component } from 'react';
import ToggleBox from '../components/ToggleBox';
class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
      total : 60,
      count: 0
    };
  }
  getToggles() {
      let toggles = [];
      for (let i = 0; i < this.state.count; i++) {
        toggles.push(<ToggleBox checked={false} key={i} />);
      }
    return toggles;
  }

  render() {
    let toggles = this.getToggles();
    return (
      <div className="App">
        {{this.state.count}} - {{this.state.total}}
        <div className="container-toggle-box">
            {toggles}
        </div>
      </div>
    );
  }
}

export default App;

注意:body需要是格式正确的JSON字符串

答案 1 :(得分:0)

您需要将语法更新为swift 3.0

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