NSURLProtocol

NSURLProtocol is both the most obscure and the most powerful part of the URL Loading System. It’s an abstract class that allows subclasses to define the URL loading behavior of new or existing schemes.

nshipster.com/nsurlprotocol/

NSURLProtocol is the most powerful (and least-known) piece of Apple’s URL Loading System. It lets you completely take over how any URL request is handled, for existing schemes (http, https, file…) or brand-new ones, without changing a single line of your networking code.

What you can do with a custom NSURLProtocol:

How it works:

  1. Subclass NSURLProtocol
  2. Implement +canInitWithRequest: → return YES for requests you want to handle
  3. Implement -startLoading → do whatever you want (load from disk, fake data, etc.) and call your client (the system) with the usual delegate methods (didReceiveResponse, didLoadData, didFinishLoading, etc.)
  4. Implement -stopLoading → clean up
  5. Register once at launch:
    NSURLProtocol.registerClass(MyProtocol.self)

Registered protocols are asked in reverse order, so yours can intercept before the built-in HTTP handler.

Bottom line:

NSURLProtocol is Apple-blessed, zero-boilerplate man-in-the-middle for all networking.
Use it for testing, debugging, offline mode, custom schemes, or secret sauce, and the rest of your app doesn’t even know it’s there.


Category:

Year: