如何在 Alamofire 中恢复 sessionTask 之前调用自定义方法

How to call custom method right before sessionTask resume in Alamofire

当 Alamofire 调用 resume 开始请求时,我需要记录一些 data/info。 (我在我的项目中使用了Swift)

反正有没有做method_swizzling

时间轴是这样的:

Call a request (put in request queue or execute right away) -> [custom method] -> SessionTask.resume()

我知道 Moya 做了类似的事 WillSend。但是我想知道不使用Moya怎么办。

谢谢。

如果您需要做的只是检查各种请求元素,您可以使用 Alamofire 5 的 EventMonitor 协议,该协议在 Alamofire 发出请求时的各种生命周期事件期间被调用。有一个内置的 ClosureEventMonitor 允许您为这些事件设置闭包。例如:

let monitor = ClosureEventMonitor()
monitor.requestDidCompleteTaskWithError = { (request, task, error) in
    debugPrint(request)
}
let session = Session(eventMonitors: [monitor])

请参阅our documentation for ClosureEventMonitor and the EventMonitor protocol itself