Swift-根据发布请求将参数添加到httpBody

时间:2018-12-17 21:26:54

标签: json swift http post

我正在发布一个URL,而我的webDev告诉我我需要设置

  

data =

作为参数,而我的JSONObject作为键。我不知道如何将字符串设置为参数。

我试图在request.httpBody上连接一个字符串,但它仅接受数据。我也尝试将其添加到其他一些区域,但无济于事。

let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        let dateString = dateFormatter.string(from: load.date)

        let json: [String: Any] = ["lb_datetime": "\(dateString)", "operator_id": "\(load.operatorID)", "ticket_number": load.ticketNumber, "timber_sale_id": "\(load.saleID)", "hauler_id": haulerInt, "product_id": String(load.productID), "destination": load.destination, "driver": load.driver, "trailer": load.trailerNumber, "trailer_drop": "\(load.trailerDrop)", "scaleticket": load.scaleTicketNumber, "tons": "\(load.tons)", "coords": coordsString, "net": "\(load.net)", "live": "true"]

        print("JSON Object: \(json)")

        let jsonData = try? JSONSerialization.data(withJSONObject: json)

        // create post request
        let url = URL(string: "http://example.net/example/app/mobile/removal/")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // insert json data to the request
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print("RESPONSEDATA: \(responseJSON)")
            }
        }

        task.resume()

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

let jsonData = try? JSONSerialization.data(withJSONObject: json)
if let _jsonData = jsonData {
    request.httpBody?.append(jsonData)
}