Synthetic Webserver with Cocoa WebView on Mac OS X
I would like to create a Webview where I have total control over the content it loads. Essentially I want to provide an instance of a class that plays the role of the various web servers named in the URLs. Ideally, I would provide this webview with a delegate and it would tell the delegate each URL it requires and the delegate would respond with the MIME type and data.
One way to do this would be to literally have a web server running on some custom port (say 2222) and supply an initial URL like http://localhost:2222/initial/base/url. However, this only allows me to intercept relative URLs on the same host, not absolute URLs to other h开发者_高级运维osts.
The WebView delegates I saw in the documentation seems to allow the user high-level control, such as choosing a policy of which URLs to load, or monitoring the progress of loads, but not the ability to intercept and control the data which is loaded itself.
Any hints on how I might achieve this goal?
NSURLProtocol serves this function. You register your class as a protocol (maybe better called a protocol handler), and every NSURLRequest will be routed to you to ask whether you can handle it. You say YES and then your object has full control over the URL loading process. This ties into the main URL loading engine, so it takes care of all WebViews, NSURLConnections, etc. See this question for some more pointers.
精彩评论