swiftfiddle-web icon indicating copy to clipboard operation
swiftfiddle-web copied to clipboard

No response if "_streaming" is false

Open HassanTaleb90 opened this issue 1 year ago • 0 comments

If "_streaming" is set to false, there will be no response. However, if it is set to true, everything works as expected:

Response: {"kind":"version","text":"Swift version 5.9.2 (swift-5.9.2-RELEASE)\nTarget: x86_64-unknown-linux-gnu\n"}
{"kind":"stdout","text":"Hello, Swift!\n"}

Code:

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-runner-functions-592.blackwater-cac8eec1.westus2.azurecontainerapps.io/runner/5.9.2/run"

let headers = [
    "Content-Type": "application/json; charset=UTF-8"
]
let script = "print(\"Hello, Swift!\")"
let jsonObject: [String : Any] = [
    "code": script,
    "toolchain_version": "5.9.2",
    "_color": false,
    "_streaming": false
]

sendPostRequest(urlString: url, headers: headers, jsonObject: jsonObject) { (data, response, error) in
    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")
    }
}

Note: I observed that the URL request for all versions follows a similar pattern, such as https://swiftfiddle-runner-functions-592.blackwater-cac8eec1.westus2.azurecontainerapps.io/runner/5.9.2/run, except for version 5.10, which utilizes a different format: https://swiftfiddle-runner.onrender.com/runner/5.10.0/run. Is there a method to utilize a uniform URL structure, similar to the previous one, such as https://swiftfiddle.com/runner/5.9.2/run?

HassanTaleb90 avatar May 05 '24 07:05 HassanTaleb90