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:
- Serve local files instead of remote ones (e.g. bundle images for offline/debug)
- Mock/stub network responses for testing
- Automatically add auth headers, sign requests, normalise parameters
- Implement custom schemes (e.g.
myapp://,embed://) - Log, filter, or redact sensitive data
- Redirect, cache, or transform responses on the fly
- Test error handling by injecting broken responses
How it works:
- Subclass
NSURLProtocol - Implement
+canInitWithRequest:→ return YES for requests you want to handle - Implement
-startLoading→ do whatever you want (load from disk, fake data, etc.) and call yourclient(the system) with the usual delegate methods (didReceiveResponse,didLoadData,didFinishLoading, etc.) - Implement
-stopLoading→ clean up - 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:
Tags:
Year: