Jonathan Hersh
Jonathan Hersh

Reputation: 1073

Alamofire: Follow HTTP redirects (or not)

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?

Upvotes: 28

Views: 11214

Answers (3)

onmyway133
onmyway133

Reputation: 48175

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

Upvotes: 7

Jonathan Hersh
Jonathan Hersh

Reputation: 1073

Flexible redirect handling is now in Alamofire thanks to another pull request and is available with Alamofire 1.2.0.

Upvotes: 10

ProllyGeek
ProllyGeek

Reputation: 15856

I think that issue has been discussed long time ago , check this issue

matt's answer was clear though :

I presume various closure-typed properties in SessionDelegate, TaskDelegate, DataTaskDelegate and DownloadTaskDelegate are intended to be used by clients to extend/override particular delegates behavior.


Actually, that's incorrect. These are implemented internally for the sake of completeness. Any functionality intended for the end user would be exposed on Manager or Request.

Anyway I see that the bounty is offered by Aaron , while Jonathan forked his own version , so why dont you use that fork ?

Upvotes: 0

Related Questions