Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taskWillPerformHTTPRedirection never called in Alamofire 5

Updating Alamofire to 5.0.4. As the title says taskWillPerformHTTPRedirection is never called.

In Alamofire 4.x we could do something like:

  let sessionDelegate =  request.session.delegate as! Alamofire.SessionDelegate

  sessionDelegate.taskWillPerformHTTPRedirection = { session, task, response, request in
    if let url = task.currentRequest?.url {
        // look at redirected url & act accordingly
      }
    }
  }

A request's session/delegate has been overhauled in Alamofire 5 and is no longer directly accessible from the request. More specifically, taskWillPerformHTTPRedirection is a closure callback on ClosureEventMonitor. As a sanity check, I tested using some of the other closure callbacks.. and they worked.

// ClosureEventMonitor

  let monitor = ClosureEventMonitor()
  monitor.requestDidCreateTask = { request, task in
     // Event fires
  }

  let monitor2 = ClosureEventMonitor()
  monitor2.taskWillPerformHTTPRedirection = { sess, task, resp, req in
   // Event Never fires
  }

  monitor2.requestDidFinish = { request in
    // Event Fires
  }

  // Set up Session
  var session: Session? = Session(startRequestsImmediately: false, eventMonitors: [monitor, monitor2])

  let url = URL(string: "https://google.com")!
  let urlRequest = URLRequest(url: url)

  let trequest = session?.request(urlRequest)

For reference this code is being fired from my AppDelegate func application(_ application: UIApplication, continue userActivity: NSUserActivity for handling deep/universal links.

I'm not exactly sure what I'm missing here. Any help is greatly appreciated. Thank you for your time.

like image 995
wambambizzle Avatar asked Nov 25 '25 05:11

wambambizzle


1 Answers

There are three things here:

First, session?.request(urlRequest) will never actually make a request, since you never call resume() (or attach a response handler).

Second, using a one off Session like that is not recommended. As soon as the Session goes out of scope all requests will be cancelled.

Third, EventMonitors cannot interact with the request pipeline, they're only observational. Instead, use Alamofire 5's new RedirectHandler protocol or Redirector type to handle redirects. There is more in our documentation. A simple implementation that customizes the action performed would be:

let redirector = Redirector(behavior: .modify { task, request, response in
    // Customize behavior.
})
session?.request(urlRequest).redirect(using: redirector)
like image 175
Jon Shier Avatar answered Nov 27 '25 18:11

Jon Shier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!