Frederik Norlyk Eriksen Frederik Norlyk Eriksen - 14 days ago 5
Swift Question

Getting HTTP headers with URLSessionDownloadDelegate

How would I go about getting the headers from the server to check it the status code is

200
,
404
, etc.?

I have a delegate class:

class DownloadDelegate : NSObject, URLSessionDelegate, URLSessionDownloadDelegate, URLSessionTaskDelegate {
// Implementations of delegate methods:
[...]didFinishDownloadingTo location: URL[...]
[...]didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64[...]
}


But I'm not sure where I can extract the headers.

Answer

urlSession(_:downloadTask:didFinishDownloadingTo:) provides you the headers.

The parameter downloadTask has an attribute .response of type URLResponse.

Assuming that you are using HTTP/HTTPS, this can be casted to HTTPURLResponse.

Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the HTTPURLResponse class.

(Source: API Reference of URLResponse)

HTTPURLResponse has properties to get the status code (statusCode) and all header fields as [AnyHashable: Any] (allHeaderFields).

Example:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    guard let response = downloadTask.response as? HTTPURLResponse else {
        return //something went wrong
    }

    let status = response.statusCode
    let completeHeader = response.allHeaderFields
}