Search code examples
swifturlsession

URLSession Response doesn't contain headers from last redirect


I have an URL that I, when called in a webbrowser, will redirect me 2 times and in the response header of the second redirect it will send the Information that I want to extract.

So to automatically extract that information in swift, I wrote this short piece of code that makes the HTTP Request and then prints the response headers:

printv(text: "Loading JSID Location")
req = URLRequest.init(url: JSIDLocation!)
var task : URLSessionDataTask
task = URLSession.shared.dataTask(with: req) {(data, response, error) in
    if let res = response as? HTTPURLResponse {
        res.allHeaderFields.forEach { (arg0) in
           let (key, value) = arg0
              self.printv(text: "\(key): \(value)")
           }
    }
    self.printv(text: String.init(data: data!, encoding: String.Encoding.utf8)!)
}
task.resume()

(printv is a function that will format the string and print it to a label)

So when I run this, I expect it to print the response headers and the body of the last redirect, but what actually happens is that i just prints response headers and body of the original URL. As those don't contain the information im looking for, that won't help me. I already googled my problem, and I found out that HTTP Redirects by default are activated in URLSessions and that you'd had to mess with URLSessionDelegates in order to deactivate them but that's definetly not something I did. Thank you for your help!


Solution

  • If you want redirect information, you need to become the URLSessionDataTaskDelegate.

    let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
    

    Then you need to implement, the redirection delegate function and be sure to call the completion handler with the given new redirect request:

    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        // operate on response to learn about the headers here
        completionHandler(request)
    }