iosobjective-chttpafnetworkingnsurlprotocol

iOS - Use AFNetworking with custom NSURLProtocol class


I have a custom NSURLProtocol class that I have implemented with the help of this tutorial. My implementations are pretty much the same as in the tutorial, aside from the names, data model, etc...

Essentially, I am trying to send a HTTP request, but instead of the URL starting with: "http://", it needs to start with, say: "bla://"

Now, I am trying to register the protocol class and use it via the AFNetworking framework, and I'm having some trouble.

The canInitWithRequest: method starts returning NO at some point, and at this point the request fails and I keep getting a "unsupported URL" error.

In addition to registering the protocol class, I have tried to add the class to AFHTTPSessionManager's protocolClasses by calling this in thedidFinishLaunchingWithOptions method:

[NSURLProtocol registerClass:[MyURLProtocol class]];
NSMutableArray *protocolsArray = [NSMutableArray arrayWithArray:[AFHTTPSessionManager manager].session.configuration.protocolClasses];
[protocolsArray addObject:[MyURLProtocol class]];
[AFHTTPSessionManager manager].session.configuration.protocolClasses = [protocolsArray copy];

And I have also added the url scheme to the URL Schemes field in the app's info.plist

Still no luck... Is what I'm trying to do even possible? And if so, what could I be missing? Thanks


Solution

  • So, for other looking for information about this:

    Along with the fact that AFURLSessionManager doesn't use the standard NSURLProtocol registrations, it also processes the array First-In-First-Out, not Last-In-First-Out like NSURLProtocol.

    Meaning, if you want to overwrite the behavior of the AFURLSessionManager (say for testing purposes), you can't just add your NSURLProtocol subclass to session.configuration.protocolClasses, you must instead add it to the beginning of the array (or at least in front of the behavior you're overwriting/modifying).