swiftnsurlsessionfoundation

Use Swift URLSession example code on command line tool


I am trying to figure out the simplest way to make an HTTP request in Swift 4 from the command line. I have copied this code from the URLSession programming guide, and added a couple print statements. I can't figure out why the .dataTask is not executing.

print("Testing URLSession")
let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default)
if let url = URL(string: "https://www.example.com/") {
    print("Encoded url \(url)")
    (sessionWithoutADelegate.dataTask(with: url) { (data, response, error) in
        print("Executing dataTask")
        if let error = error {
            print("Error: \(error)")
        } else if let response = response,
            let data = data,
            let string = String(data: data, encoding: .utf8) {
            print("Response: \(response)")
            print("DATA:\n\(string)\nEND DATA\n")
        }
    }).resume()
}

The objective is to retrieve data from a REST api, but I can't even make a simple GET request to work properly...


Solution

  • I finally figured out how to make it work using CFRunLoop:

    let runLoop = CFRunLoopGetCurrent()
    let task = session.dataTask(with: request) { (data, response, error) in
        print("Retrieved data")
        CFRunLoopStop(runLoop)
    }
    task.resume()
    CFRunLoopRun()
    print("done")