Search code examples
swiftnsurlrequest

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


Subject says it all. We want to make a URLRequest where all we care about is the HTTP return code (e.g. 200, 400, etc.) which we can get from the httpUrlResponse object. What we don't need is a response body, since there isn't one.

Here's how you make a request that expects a response body...

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()

But how do you do it if you don't want/need responseBodyData? Or do you just use the same code, ignoring the responseBodyData field, replacing it with _ since it is optional and can be ignored?


Solution

  • From your comment:

    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.

    No. The closure signature is predefined: it must take three parameters. The names don’t matter, but the number does:

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

    If you want to ignore the first parameter, ignore it (i.e. don’t refer to it again within the curly braces). You can, if you like, substitute an underscore to signal to yourself that you don’t care about the first parameter:

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

    But there is no requirement that you do that; the compiler doesn’t care one way or the other.