NSURLSession interception redirection does not work

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 send a request to add the product to the cart. This post request creates a cookie basket and redirects me to a different url. But my attempts to catch the redirect and then set cookies and other header data to the following url do not work :( Any idea why?

+4
source share
1 answer

Not sure if this is what you need, but if you just want to move cookies from the request to another, you can use NSHTTPCookieStorage .

URL-, , .

:

    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:originalResponse.URL];
   [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:originalResponse.URL mainDocumentURL:nil];

, :

[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:originalResponse.URL];
+1

Source: https://habr.com/ru/post/1616738/


All Articles