开发者

Substituting local resources by detecting URL scheme

开发者 https://www.devze.com 2023-04-03 13:37 出处:网络
I have built a class that 开发者_如何学Gointercepts UIWebView resource loading by subclassing NSURLCache and overriding cachedResponseForRequest:, similar to this example.Basically, if the requested r

I have built a class that 开发者_如何学Gointercepts UIWebView resource loading by subclassing NSURLCache and overriding cachedResponseForRequest:, similar to this example. Basically, if the requested resource is of type .css, I look for it in a local caches directory and if found, I load the local version.

The problem is that I now want to be able to specify which css files to look for in local cache, by providing a specific scheme that my app knows about. But when I change the scheme to something like:

 myapp://www.myhost.com/static/default.css

then cachedResponseForRequest: no longer gets called when the html is being loaded. Does anyone know why this, or how I can enable this method for my url with a specific scheme?


The key is to register your own subclass of NSURLProtocol, which can respond to your custom scheme in order to load those special resources. I used the following two methods:

#pragma mark - Public

+ (void)enable {
    [NSURLProtocol registerClass:[MyAppURLProtocol class]];
}

#pragma mark - NSURLProtocol Overridden methods

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    NSString *urlScheme = [[request URL] scheme];
    return [urlScheme isEqualToString:@"myapp"];
}

To register, call [MyAppURLProtocol enable] from the app delegate. You also need to override all other required methods defined in the NSURLProtocol reference, which ultimately forces you to load the data yourself..

The reason why it is necessary to register your own url protocol is documented by apple as:

The URL loading system design allows a client application to extend the protocols that are supported for transferring data. The URL loading system natively supports http, https, file, and ftp protocols.

Custom protocols are implemented by subclassing NSURLProtocol and then registering the new class with the URL loading system using the NSURLProtocol class method registerClass:...

0

精彩评论

暂无评论...
验证码 换一张
取 消