如何执行没有 have/need 响应主体的 URLRequest?

How can you execute a URLRequest that doesn't have/need a response body?

主题说明了一切。我们想创建一个 URLRequest,我们只关心 HTTP return 代码(例如 200、400 等),我们可以从 httpUrlResponse 对象中获取这些代码。我们不需要的是响应体,因为没有。

以下是如何发出需要响应正文的请求...

let urlRequest = [insert code to make request]
let urlSession = [insert code to make session]

let task = urlSession.dataTask(with: urlRequest) {

    (responseBodyData, httpUrlResponse, error) in

    if let error = error {
        // handle error
        return
    }

    guard let responseBodyData = responseBodyData else {
        // Handle missing data
        return
    }
}

task.resume()

但是不want/needresponseBodyData怎么办呢?或者您只是使用相同的代码,忽略 responseBodyData 字段,将其替换为 _ 因为它是可选的并且可以忽略?

来自您的评论:

What I'm wondering is if that's the correct way. In other words, was there something else that didn't have that parameter--a different closure signature or something.

没有。闭包签名是预定义的:它必须 采用三个参数。名字并不重要,但数字很重要:

let task = urlSession.dataTask(with: urlRequest) {(body, response, err) in

如果你想忽略第一个参数,忽略它(即不要在花括号内再次引用它)。如果愿意,您可以用下划线代替,以向自己表明您不关心第一个参数:

let task = urlSession.dataTask(with: urlRequest) {(_, response, err) in

但是没有要求你这样做;编译器不关心其中一种方式。