Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用命令行工具上的Swift URLSession示例代码_Swift_Nsurlsession_Foundation - Fatal编程技术网

使用命令行工具上的Swift URLSession示例代码

使用命令行工具上的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/") {

我正试图找出在Swift 4中从命令行发出HTTP请求的最简单方法。我从中复制了这段代码,并添加了一些打印语句。我不明白为什么
.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工作的内容。