我正试图找出 最简单的 在Swift 4中从命令行发出HTTP请求的方法。我已从 URLSession programming guide ,并添加了几个打印语句。我不明白为什么 .dataTask 未执行。
.dataTask
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() }
GET 请求正常工作。。。
GET
我终于想出了如何使用 CFRunLoop
CFRunLoop
let runLoop = CFRunLoopGetCurrent() let task = session.dataTask(with: request) { (data, response, error) in print("Retrieved data") CFRunLoopStop(runLoop) } task.resume() CFRunLoopRun() print("done")