NSURLSession catch redirect not working

I have a class:


    class Test: UIViewController, NSURLSessionDelegate {
  
        func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
            let responseHeaderFields = (response ).allHeaderFields as! [String : String]
            var nR = NSMutableURLRequest(URL: request.URL!, cachePolicy:  NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: NSTimeInterval(30))
            nR.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaderFields, forURL: response.URL!))

                for header in responseHeaderFields {
                    nR.setValue(
                        header.1,
                        forHTTPHeaderField: header.0
                    )
                }      
                completionHandler(nR)
            }
  
        func myMethod() {
              //some code...

              let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
              let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
              session.dataTaskWithRequest(urlRequest, completionHandler: {
                (data:NSData?, response:NSURLResponse?, error:NSError?) in
                    guard let responseData = data else {
                        return
                    }
                    guard error == nil else {
                        return
                    }
                    //....
            }
        }

    }

When i call myMethod i do post request to add item to cart. This post request create cookie for cart and redirect me to another url. But my attempts to catch redirect and then set cookies and another headers data to next url is not working 😟 Any idea why ?

I assume you've double checked that the method signature on your delegate method is correct.


Does your delegate get called if you use dataTaskWithRequest() (no completion handler) or pass nil for the completion handler? Maybe the delegate callbacks are all-or-none - not sure.

- I cannot find task.resume() in your code. Is it included in the `//....`? Also I needed to fill unmatching `)`.

- Xcode claims delegate method signature should be:

func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void)

The type of `completionHandler` is (NSURLRequest?) -> Void, not (NSURLRequest!) -> Void .

- In general, you have no need to handle redirection by yourself. NSURLSession and its tasks will do it appropriately, including cookie handling.

- Usual browsers do not send back all header fields included in the redirecting response header. In some cases, sending back all may cause problems.


You might need to handle HTTPCookieStorage properly, rather than implementing redirection delegate method.

I know this is old, but google brought me here, and I later solved it. The issue is that willPerformHTTPRedirection is in NSURLSessionTaskDelegate (note Task in there) not NSURLSessionDelegate, and so you need your class to specify that it conforms to NSURLSessionTaskDelegate

NSURLSession catch redirect not working
 
 
Q