2

I try to add a custom NSURLProtocol to a NSURLSession in order to serve test data for some calls, while providing the normal internet connectivity for all other calls. I need to do this by adding the NSURLProtocol to the session configuration's protocolClasses, as the session resides in a library that is included in the project.

For some reason my setup does deliver the test data right when my custom protocol takes the request by returning true for the canInitWithRequest call, but for all other requests (when it returns false) the default protocols that are still in the protocolClasses behind my custom protocol get the request and even return true on the canInitWithRequest call, but they never send the request to the internet and deliver a request timeout after 30 seconds instead. When I remove my custom protocol from the protocolClasses, everything works fine - just my test data is not served anymore, of course.

This is the code I use for installing the protocol:

    NSURLSessionConfiguration* sessionConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSMutableArray* protocols = [NSMutableArray arrayWithArray:sessionConfiguration.protocolClasses];
    [protocols insertObject:[MyProtocol class] atIndex:0];
    sessionConfiguration.protocolClasses = protocols;
    mySession = [NSURLSession sessionWithConfiguration:sessionConfiguration];

When I register the custom protocol with [NSURLProtocol registerClass:[MyProtocol class]], the fallthrough does work, but as written I can't use this approach in my project.

Any idea on why this is not working correctly?

TheEye
  • 9,280
  • 2
  • 42
  • 58

1 Answers1

0

Firstly there is a misprint in your code snippet, it should be protocols instead of array variable. ))

I think that in case of custom protocol, it makes sense to see protocol client and so on( propertyFoKey: inRequest:) Is the method startLoading(or stopLoading) is called?

Ah, I have re read your question.

In case of [NSURLProtocol registerClass] , the custom class, if being the latest registered, will handle URL scheme. In your case it seems that there is another(void) protocol that handles the request.

  • Thanks for the misspelling tip, corrected. I stepped into the debugger and found that the internal class _NSURLHTTPProtocol is called for falling through http requests, and it even returns true for the canInitWithRequest call, - it's just not doing anything anymore after that ... – TheEye Jun 04 '15 at 11:02
  • add your protocol as a last element into the array, rebuild app, should help)) – Siarhei Yakushevich Jun 04 '15 at 11:25
  • 1
    then the default http protocol catches the request first and my specific protocol does not get the chance to catch eg "http://testdata.com" and return the test data, as the http protocol will try to handle the http address ... – TheEye Jun 04 '15 at 12:03