在命令行工具上使用Swift URLSession示例代碼

[英]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.

我試圖找出從命令行在Swift 4中發出HTTP請求的最簡單方法。我已從URLSession編程指南中復制了此代碼,並添加了幾個打印語句。我無法弄清楚為什么.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()
}

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

目標是從REST API中檢索數據,但我甚至無法使一個簡單的GET請求正常工作......

1 个解决方案

#1


2  

I finally figured out how to make it work using 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")

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/09/20/72fc8489775f58a990c23a290ad1fb79.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com