I'm trying to configure Alamofire to follow redirects (or not) on a per-request basis.
Alamofire has a private internal class SessionDelegate
which serves as the NSURLSessionTaskDelegate
for the current URL session. SessionDelegate
does implement the relevant delegate method, URLSession(session:, task:, willPerformHTTPRedirection response:, request:, completionHandler:)
which is exactly what I want.
Even better, the delegate's implementation consults a custom variable closure named taskWillPerformHTTPRedirection
to determine how to handle the redirect - again, exactly what I want!
And as far as I can tell, that closure is always nil
by default -- it is not assigned to internally by Alamofire -- which suggests that it is intended to let the user assign a closure to it.
The problem: I cannot access this private SessionDelegate
class to assign a closure to its taskWillPerformHTTPRedirection
variable. It is a private class and it is not visible to my Swift files. What is the proper means of configuring an Alamofire request to (not) follow redirects?
Flexible redirect handling is now in Alamofire thanks to another pull request and is available with Alamofire 1.2.0
.
You can use it like this
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let sessionDelegate = Manager.SessionDelegate()
sessionDelegate.taskWillPerformHTTPRedirectionWithCompletion = {
(session: NSURLSession, task: NSURLSessionTask, response: NSHTTPURLResponse,
newRequest: NSURLRequest, completionHandler: NSURLRequest? -> Void) in
// do something
}
let manager = Manager(configuration: configuration, delegate: sessionDelegate)
Alamofire Manager keeps the delegate
as strong so you can be sure
public let delegate: SessionDelegate
but remember willPerformHTTPRedirection
This method is called only for tasks in default and ephemeral sessions. Tasks in background sessions automatically follow redirects.
also good to read about fundamentals Handling Redirects and Other Request Changes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With