How to programmatically monitor all incoming and outgoing requests that my app is making using URLSession
?
The goal is to see data like URL, headers and body of those requests.
Perhaps something similar to this but using code within my app.
This should work in production and should be able to listen to the requests made by third party libraries, too.
2
Answers
you can have a look at the source of
Moya
.If you want to track only requests (but not responses), then it’s as simple as adding an extra layer of
NSURLProtocol
to the session object. Since public API of theNSURLSession
accepts tasks only, you can limit tracking tocanInitWithTask:
method:You cannot omit implementation of
canInitWithRequest:
because in this case URL loading system will forward it to the base implementation ofNSURLProtocol
, which throws an error (the class is considered abstract). You provide your custom protocol to aNSURLSession
instance by incorporating it to the configuration’sprotocolClasses
property:If you additionally want to track all requests made by the
sharedSession
instance you must register your class globally withNSURLProtocol
helper methods:This also makes URL loading system to forward web views to requests to your protocol class.
You may want to track
canInitWithRequest:
invocations as well, but be advised that in this case you will also get modified requests from internal implementation in addition to the original requests.