Implement URLProtocol but respect session configuration

553 Views Asked by At

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:

  1. Extract the session (and the configuration) from the task. Cons: exposing a private property not guaranteed to exist.
  2. Give up on URLProtocol and swizzle a bunch of URLSession and URLSessionTask methods. Cons: requires a lot of swizzling.
  3. ?
0

There are 0 best solutions below