使用命令行工具上的Swift URLSession示例代码
我正试图找出在Swift 4中从命令行发出HTTP请求的最简单方法。我从中复制了这段代码,并添加了一些打印语句。我不明白为什么使用命令行工具上的Swift URLSession示例代码,swift,nsurlsession,foundation,Swift,Nsurlsession,Foundation,我正试图找出在Swift 4中从命令行发出HTTP请求的最简单方法。我从中复制了这段代码,并添加了一些打印语句。我不明白为什么.dataTask没有执行 print("Testing URLSession") let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default) if let url = URL(string: "https://www.example.com/") {
.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()
}
目标是从REST api检索数据,但我甚至不能发出一个简单的
GET
请求来正常工作…我终于找到了如何使用CFRunLoop
使其工作的方法:
let runLoop = CFRunLoopGetCurrent()
let task = session.dataTask(with: request) { (data, response, error) in
print("Retrieved data")
CFRunLoopStop(runLoop)
}
task.resume()
CFRunLoopRun()
print("done")
我终于想出了如何使用
CFRunLoop
:
let runLoop = CFRunLoopGetCurrent()
let task = session.dataTask(with: request) { (data, response, error) in
print("Retrieved data")
CFRunLoopStop(runLoop)
}
task.resume()
CFRunLoopRun()
print("done")
这是在iOS或macOS应用程序中还是在命令行应用程序中?或者在操场上?这是在命令行应用程序中。我在操场上试过,但它似乎没有正常工作,因为它停止在右边显示值,甚至对于打印语句……在结束的大括号后有代码吗,或者程序结束在那里?
URLSessionTask
异步运行,因此如果程序在完成之前结束,您将永远看不到其结果。将此PlaygroundPage.current.NeedsDefiniteExecution=true
添加到Playground中仍然无法使Playground工作。这是在iOS或macOS应用程序中还是在命令行应用程序中?或者在操场上?这是在命令行应用程序中。我在操场上试过,但它似乎没有正常工作,因为它停止在右边显示值,甚至对于打印语句……在结束的大括号后有代码吗,或者程序结束在那里?URLSessionTask
异步运行,因此如果程序在完成之前结束,您将永远看不到其结果。将此PlaygroundPage.current.needsIndefiniteExecution=true
添加到Playground添加仍然无法使Playground工作的内容。