简体   繁体   中英

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.

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, EventMonitor s 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM