Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 755
Developer Avatar asked Aug 09 '26 22:08

Developer


1 Answers

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
}
like image 120
FelixSFD Avatar answered Aug 15 '26 22:08

FelixSFD