Search code examples
swiftapianimationalamofireloading

Catch every time an API call is made regardless of call in swift with Alamofire?


I am not sure what terminology to use, so pardon me if it's wrong. Hopefully I can still be clear what I am looking for. I want to have a loading animation appear anytime I make an API call. I would like to have the code centralized, and called anytime I make an API call, instead of writing code manually for each API call. Is this possible? Is there some way to catch any API call that is made and call the code to show the loading animation?


Solution

  • You can use Alamofire's EventMonitor protocol to accomplish this. EventMonitor gives you callbacks during various Alamofire events, like when requests start and finish. The events you may be interested in would be requestDidResume or request(_:didResumeTask:)) and requestDidFinish (or request(_:didCompleteTask:with:)). Alamofire also includes the ClosureEventMonitor, in case you don't want to write your own, where you can set closures to be called during the events.

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