Cannot use URLSession in a Swift Package

I created an executable Swift package and when I do a simple HTTP request such as:

func request() {

    let url = URL(string: "https://httpbin.org/get")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        print("Test") // Never executed
        if let error = error {

            print("error: \(error)")

        } else {

            if let response = response as? HTTPURLResponse {

                print("statusCode: \(response.statusCode)")

            }

            if let data = data, let dataString = String(data: data, encoding: .utf8) {

                print("data: \(dataString)")

            }

        }

    }

    task.resume()

}



request()

It simply does not execute the code inside of dataTask.

Answered by ChristopheDev in 684315022

I had to run RunLoop.current.run() at the end of my script for it to run the asynchronous code.

Accepted Answer

I had to run RunLoop.current.run() at the end of my script for it to run the asynchronous code.

Cannot use URLSession in a Swift Package
 
 
Q