I want to intercept all network calls (request and response) in an application, so I'm implementing a concrete URLProtocol subclass.
Most online examples simply create a new URLSession with the default configuration for each task. Which means that any configuration from the originating session is lost.
One approach is to store the task from init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) and resume it in startLoading(), but then there is no way to get notified of the task results.
It seems I can either create a new session and loose the configuration, or reuse the session but not get notified of the task events, but not both.
Question: how do I implement URLProtocol, more precisely startLoading(), so that the session configuration is not lost, and I still get the task's delegate callbacks?
Ideas:
- Extract the session (and the configuration) from the task. Cons: exposing a private property not guaranteed to exist.
- Give up on
URLProtocoland swizzle a bunch ofURLSessionandURLSessionTaskmethods. Cons: requires a lot of swizzling. - ?