UIWebView (NSURLProtocol)拦截js、css
<p>公司最近有个需求,去除h5页面的广告,最后实现的方式是后台去过滤,移动端这里只需要拦截里面的一个css地址重定向就可以.开会的时候以为很简单,毕竟 UIWebView 协议方法里面有个每次请求都会走的协议方法 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 实际开发的过程当中才发现这是行不通的.</p> <p>中间过程就不说了.结果肯定是可以做到的,用到了神奇的 <strong>NSURLProtocol</strong></p> <p>这里主要做下笔记:</p> <h2>NSURLProtocol</h2> <p>它是干什么的呢,是一个挺牛逼的类,它是一个抽象类,不能去实例化它,只能子类化 NSURLProtocol ,</p> <p>每次在对一个 URL 进行请求的时候 URL Loading System 都会向 已经注册的 Protocol 询问是否可以处理该请求。这里就看出他的作用来了. <strong>比如</strong> : 拦截UIWebView的请求,忽略请求,重定向... ...</p> <h2>如何使用NSURLProtocol</h2> <ul> <li> <p>创建</p> </li> </ul> <pre> <code class="language-objectivec">#import @interface FilteredProtocol : NSURLProtocol @end </code></pre> <ul> <li> <p>在合适的地方注册(demo是在 appdelegate 类中)</p> </li> </ul> <pre> <code class="language-objectivec">[NSURLProtocol registerClass:[FilteredProtocol class]];</code></pre> <ul> <li> <p>取消注册,一般在加载完成或 dealloc 方法里面取消</p> </li> </ul> <pre> <code class="language-objectivec">[NSURLProtocol unregisterClass:[FilteredProtocol class]];</code></pre> <ul> <li> <p>重写父类方法</p> </li> </ul> <pre> <code class="language-objectivec">+ (BOOL)canInitWithRequest:(NSURLRequest *)request; + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b; - (void)startLoading; - (void)stopLoading;</code></pre> <p>一个个的说</p> <pre> <code class="language-objectivec">+ (BOOL)canInitWithRequest:(NSURLRequest *)request;</code></pre> <p>这个方法是决定这个 protocol 是否可以处理传入的 request 的如是返回 true 就代表可以处理,如果返回 false 那么就不处理这个 request 。</p> <pre> <code class="language-objectivec">+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;</code></pre> <p>这个方法主要是用来返回格式化好的 request ,如果自己没有特殊需求的话,直接返回当前的request就好了。如果你想做些其他的,比如地址重定向,或者请求头的重新设置,你可以 cop y下这个 request 然后进行设置。</p> <pre> <code class="language-objectivec">+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;</code></pre> <p>该方法主要是判断两个请求是否为同一个请求,如果为同一个请求那么就会使用缓存数据。通常都是调用父类的该方法。</p> <pre> <code class="language-objectivec">- (void)startLoading;- (void)stopLoading;</code></pre> <p>开始处理这个请求和结束处理这个请求</p> <p>我们处理(拦截)好请求之后,就要开始对他经常处理,这个时候就用到了父类里面的 client 对象.</p> <pre> <code class="language-objectivec">/*! @method client @abstract Returns the NSURLProtocolClient of the receiver. @result The NSURLProtocolClient of the receiver. */ @property (nullable, readonly, retain) id client; </code></pre> <p>他是一个协议,里面的方法和 NSURLConnection 差不多</p> <pre> <code class="language-objectivec">- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse; - (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse; - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy; - (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data; - (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol; - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; - (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;</code></pre> <ul> <li> <p>实际应用(拿我拦截css为例子)</p> <ul> <li> <p>需求是要去掉下面图片上 立刻下载 的广告:</p> </li> </ul> </li> </ul> <p style="text-align:center"><img src="https://simg.open-open.com/show/4ca332cb6b80b259bd73d5f9181fec79.png"></p> <p>我是原图</p> <ul> <li> <p>这是运行后打印的log</p> </li> </ul> <p><img src="https://simg.open-open.com/show/2b25037dadf5eefbc468549653e94015.png"></p> <p>运行ing</p> <p>上图可以看到截获的所有的请求地址,不管是js,css还是png图片都有</p> <ul> <li> <ul> <li> <p>这是代码运行后的效果</p> </li> </ul> </li> </ul> <p style="text-align:center"><img src="https://simg.open-open.com/show/8e595c89465e9ddcc352abe38adf67a1.png"></p> <p>我是最终效果图</p> <ul> <li> <ul> <li> <p>代码如下:</p> </li> </ul> </li> </ul> <pre> <code class="language-objectivec">static NSString*const sourUrl = @"http://cdn.web.chelaile.net.cn/ch5/styles/main-1cb999d572.css"; static NSString*const localUrl = @"http://h5apps.scity.cn/hack/cdn.web.chelaile.net.cn/ch5/styles/main-1cb999d572.css"; static NSString*const FilteredCssKey = @"filteredCssKey"; @interface FilteredProtocol () @property (nonatomic, strong) NSMutableData *responseData; @property (nonatomic, strong) NSURLConnection *connection; @end</code></pre> <pre> <code class="language-objectivec">@implementation FilteredProtocol + (BOOL)canInitWithRequest:(NSURLRequest *)request { NSLog(@"request.URL.absoluteString = %@",request.URL.absoluteString); //只处理http和https请求 NSString *scheme = [[request URL] scheme]; if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame )) { //看看是否已经处理过了,防止无限循环 if ([NSURLProtocol propertyForKey:FilteredCssKey inRequest:request]) return NO; return YES; } return NO; }</code></pre> <pre> <code class="language-objectivec">+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { NSMutableURLRequest *mutableReqeust = [request mutableCopy]; //截取重定向 if ([request.URL.absoluteString isEqualToString:sourUrl]) { NSURL* url1 = [NSURL URLWithString:localUrl]; mutableReqeust = [NSMutableURLRequest requestWithURL:url1]; } return mutableReqeust; }</code></pre> <pre> <code class="language-objectivec">+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b { return [super requestIsCacheEquivalent:a toRequest:b]; }</code></pre> <pre> <code class="language-objectivec">- (void)startLoading { NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy]; //给我们处理过的请求设置一个标识符, 防止无限循环, [NSURLProtocol setProperty:@YES forKey:FilteredCssKey inRequest:mutableReqeust]; BOOL enableDebug = NO; //这里最好加上缓存判断 if (enableDebug) { NSString *str = @"写代码是一门艺术"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL MIMEType:@"text/plain" expectedContentLength:data.length textEncodingName:nil]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; [self.client URLProtocol:self didLoadData:data]; [self.client URLProtocolDidFinishLoading:self]; } else { self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self]; } }</code></pre> <pre> <code class="language-objectivec">- (void)stopLoading { if (self.connection != nil) { [self.connection cancel]; self.connection = nil; } }</code></pre> <pre> <code class="language-objectivec">#pragma mark- NSURLConnectionDelegate - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self.client URLProtocol:self didFailWithError:error]; } #pragma mark - NSURLConnectionDataDelegate - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.responseData = [[NSMutableData alloc] init]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; [self.client URLProtocol:self didLoadData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self.client URLProtocolDidFinishLoading:self]; } @end</code></pre> <h2>注意点:</h2> <ul> <li> <p>Protocols的 遍历是反向的,也就是最后注册的Protocol会被优先判断。就是先注册A再注册B ,优先判断B</p> </li> <li> <p>一定要注意标记请求,不然你会无限的循环下去。。。因为一旦你需要处理这个请求,那么系统会创建你这个 protocol 的实例,然后你自己又开启了 connection 进行请求的话,又会触发 URL Loading system 的回调。系统给我们提供了 + (void)setProperty:(id)value forKey:(NSString *)key inRequest:(NSMutableURLRequest *)request; 和 + (id)propertyForKey:(NSString *)key inRequest:(NSURLRequest *)request; 这两个方法进行标记和区分。</p> </li> </ul> <p> </p> <p>来自:http://www.cocoachina.com/ios/20161202/18261.html</p> <p> </p>
本文由用户 LesJobson 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!