使用Swift发送JSON数据

时间:2017-11-30 04:42:49

标签: json swift

我正在构建一个聊天应用程序,我了解如何接收数据,但我在发送数据时遇到问题。我试图获取两个UITextField值,即用户名和消息并发送数据。

变量

@IBOutlet weak var username: UITextField!
@IBOutlet weak var textBox: UITextField!

请求接收

@IBAction func sendMessage(_ sender: UIButton) {
    let parameters = ["user": username.text, "message": textBox.text] as! [String: String]

    //create the url with NSURL
    let url = NSURL(string: "http://website.com/getChatLogJSON.php")

    //create the session object
    let session = URLSession.shared

    //now create the NSMutableRequest object using the url object
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

    } catch let error {
        print(error.localizedDescription)
    }

    //HTTP Headers
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
                print(json)
                // handle json...
            }

        } catch let error {
            print(error.localizedDescription)
        }

    })

    task.resume()

}

1 个答案:

答案 0 :(得分:-1)

Checkout SwiftyJSON,它是满足您JSON需求的整洁库。

将数据插入JSON对象变得如此简单:

json["name"] = JSON("new-name")
json[0] = JSON(1)
json["id"].int =  1234567890
json["coordinate"].double =  8766.766
json["name"].string =  "Jack"
json.arrayObject = [1,2,3,4]
json.dictionaryObject = ["name":"Jack", "age":25]

这是github页面,所有说明都在https://github.com/SwiftyJSON/SwiftyJSON

如果它包含您需要输入的所有数据,您可以根据需要返回字符串中的原始json并发送可以解析的数据

//convert the JSON to a raw String
if let rawString = json.rawString() {
  //Do something you want
} else {
    print("json.rawString is nil")
}