Map Custom URL Protocol for HTTP (using NSURLProtocol?)

I have an application using WebKit WebView, and I would like to map the URL loaded into this WebView using the custom URL protocol to another HTTP URL. For example, let's say I load:

custom: // path / to / resource

I would like to actually download:

http://something-else.com/path/to/resource

In other words, the user protocol serves almost like an abridged version. However, I cannot use -webView: resource: willSendRequest: redirectResponse: fromDataSource: because I want WebKit to truly believe that this is the URL in question, and not just a redirect from one to the other.

So far, I have been trying to use a custom subclass of NSURLProtocol. However, this turned out to be more complicated than I thought before, because at least as far as I know, I will have to load myself into the startLoading method of the NSURLProtocol subclass. I would just like to hand over the work to the existing HTTP protocol loader, but I cannot find an easy way to do this.

Does anyone have any recommendations on this, or perhaps an alternative way to solve this problem?

Thanks!

+7
cocoa webkit nsurlprotocol
source share
2 answers

I am using a policy delegate. It has some flaws, but it is simple and sufficient for my needs. I am doing something like this:

- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener; { if ([request.URL.scheme isEqualToString:@"custom"]) { // do something interesting // like force the webview to load another URL [listener ignore]; return; } [listener use]; } 

For my use, I also need to stop the distribution of JS events. Therefore, I usually put the URL in the onclick event handler, which calls window.event.stopPropagation (); after setting location.href.

This is not very interesting, but it is a very flexible and very simple way to associate a JS event with cocoa.

+3
source

You can implement the WebResourceLoadDelegate method:

 - (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource 

This will allow you to change the request to one with an HTTP URL.

Alternatively, implementing the NSURLProtocol subclass for this is not very complicated, because your protocol can internally run another NSURLConnection using the correct HTTP URL and map its delegation methods to the protocol client.

0
source

All Articles