Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
Jonathan Hersh Avatar asked Jan 03 '15 20:01

Jonathan Hersh


2 Answers

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

like image 166
Jonathan Hersh Avatar answered Nov 20 '22 05:11

Jonathan Hersh


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

like image 7
onmyway133 Avatar answered Nov 20 '22 04:11

onmyway133