URLSession 的 dataTask 不是 运行

dataTask of URLSession not running

我正在尝试从 API 中获取结果,但 运行 处理请求本身时遇到了问题。

这是我目前拥有的代码:

let url = URL(string: "https://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
        print("error: \(error)")
    } else {
        if let response = response as? HTTPURLResponse {
            print("statusCode: \(response.statusCode)")
        }
        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print("data: \(dataString)")
        }
    }
}
task.resume()

但是,它似乎 运行 dataTask 中的代码块内没有任何内容。

感谢您的帮助:)

您的代码运行良好。看起来你只是错误地调用了函数......这样试试:

1:

    func request() {
    let url = URL(string: "https://httpbin.org/get")!
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error {
            print("error: \(error)")
        } else {
            if let response = response as? HTTPURLResponse {
                print("statusCode: \(response.statusCode)")
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("data: \(dataString)")
            }
        }
    }
    task.resume()
}

2:

    override func viewDidLoad() {
    super.viewDidLoad()

    request()
}