let url = "http://httpbin.org/post". // Change to the actual URL
let dataToSend = ["foo": ["bar": "baz"]] // Change to the actual data
// body needs to be of type Data, use SwiftyJSON to convert
let body = try! JSON(dataToSend).rawData()
// HTTP.request() takes a callback that is called when the response is
// ready. Set up result to extract the data from the callback
var result: [String:Any] = ["result": "No response"];
// create the request
var options: [ClientRequest.Options] = [
.schema(""),
.method("POST"),
.hostname(url),
.headers(["Content-Type": "application/json"])
]
let request = HTTP.request(options) { response in
do {
let str = try response!.readString()!
if let jsonDictionary = JSON.parse(string: str).dictionaryObject {
result = jsonDictionary // we got back JSON
} else {
result = ["error": "Unknown data format returned"]
}
} catch {
print("Error \(error)") // error handling here
}
}
request.write(from: body) // add body data to request
request.end() // send request
// result now has a dictionary with either an "error" key or the data returned
// by the server