Preventing Alamofire redirect

I want to NOT follow the redirect, I want to simply stop the redirect and maybe get some info from the response.

Curl request

Plain request to google.com redirects to google.jp (since I am in Japan)
curl -v http://google.com
...
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.co.jp/?gfe_rd=cr&ei=iFSUWenOIajEXun8iKAN
< Content-Length: 259
< Date: Wed, 16 Aug 2017 14:19:52 GMT
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
...
</HTML>
* Connection #0 to host google.com left intact

Alamofire request

// Prevent automatic redirects
let delegate = Alamofire.SessionManager.default.delegate
delegate.taskWillPerformHTTPRedirection = { (_, _, _, _) -> URLRequest? in
    return nil
}

Alamofire.request("http://google.com", method: .get, headers: [:])
    .validate(statusCode: 302..<303)
    .response { (res: DefaultDataResponse) in
        
        // Make sure "Location" header is present and its url is parsed correctly
        guard let response = res.response, 
            let location = response.allHeaderFields["Location"] as? String,
            let url = URL(string: location),
            let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { 
            return
        }

        // Make sure we get the query parameter we are interested in
        guard let ei = components.queryItems?.first(where: {
            return $0.name == "ei" && $0.value != nil && !($0.value!.isEmpty)
        })?.value else {
            return
        }

        // VoilĂ 
        print("ei query parameter: \(ei)") // iFSUWenOIajEXun8iKAN
}

I skipped the proper error handling, but I think this shows the minimal code required for handling 302 responses.

To restore to original behaviour

Simply assign nil to the handler:
// Restore to original behaviour
let delegate = Alamofire.SessionManager.default.delegate
delegate.taskWillPerformHTTPRedirection = nil
I hope it helps :]

0 comments :

This work is licensed under BSD Zero Clause License | nacho4d ®