import Foundation
func sendPostRequest(urlString: String, headers: [String: String], jsonObject: [String: Any], completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
// Convert the JSON object to Data
guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject) else {
print("Error converting JSON object to data")
return
}
// Create the URL
guard let url = URL(string: urlString) else {
print("Invalid URL")
return
}
// Create the request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = jsonData
// Create the URLSession and task
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: completion)
// Start the task
task.resume()
}
// Example usage
let url = "https://swiftfiddle.com/runner/5.9.2/run"
let headers = [
"Content-Type": "application/json; charset=UTF-8"
]
let script = "print(\"Hello, Swift!\")" // Replace this with your actual script
let jsonObject = [
"code": script
]
sendPostRequest(urlString: url, headers: headers, jsonObject: jsonObject) { (data, response, error) in
// Handle the response here
if let error = error {
print("Error: \(error)")
} else if let data = data {
if let resultString = String(data: data, encoding: .utf8) {
print("Response: \(resultString)")
} else {
print("Unable to convert data to string")
}
} else {
print("No data received")
}
}
Response: {"output":"Hello, Swift!\n","errors":"","version":"Swift version 5.9.2 (swift-5.9.2-RELEASE)\nTarget: x86_64-unknown-linux-gnu\n"}