使用UIWebView加载一个网址,这个网址会发很多请求去服务器请求数据(eg:html,js,css,img),客户端通过NSURLProtocol是都可以拦截到的(发送的每个详细请求,返回的数据)。
我们根据url判断哪个请求需要拦截,然后把拦截下来的报文修改后返回给UIWebView。这样我们就基本动态的在h5里面插入了自己想要的代码。
1.在UIWebView所在的controller注册
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLProtocol registerClass:[MyConnectionURLProtocol class]];
......
}
2.MyConnectionURLProtocol实现
.h
#import <Foundation/Foundation.h>
@interface MyConnectionURLProtocol : NSURLProtocol
@end
.m
#import "MyConnectionURLProtocol.h"
@interface MyConnectionURLProtocol () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSURLConnection * connection;
@end
@implementation MyConnectionURLProtocol
//
//返回YES表示要拦截处理 走的第一个方法
//
+ (BOOL)canInitWithRequest:(NSMutableURLRequest *)request {
NSMutableURLRequest *mutableReq = [request mutableCopy];
NSMutableDictionary *headers = [mutableReq.allHTTPHeaderFields mutableCopy];
//
//防止循环 因为拦截的请求也会走这个方法
//
if (![headers[@"Key1"] isEqualToString:@"AAAA" ]){
return YES;
}
return NO;
}
//
//修改请求头 防止死循环
//
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest setValue:@"AAAA" forHTTPHeaderField:@"Key1"];
return mutableRequest;
}
//
//开始加载
//
- (void)startLoading{
NSMutableURLRequest *request = [self.request mutableCopy];
if ([request.URL.absoluteString containsString:@"http://www.我需要更改的页面.html"]) {
NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL]
statusCode:200
HTTPVersion:@"1.1"
headerFields:nil];
//
//如果是需要更改的页面则直接把数据返回给它 这个文件里的代码是通过第一次打印复制出来更改后的
//
NSString *myStr = [[NSBundle mainBundle]pathForResource:@"demopage" ofType:@"html" inDirectory:nil];
NSData *localdata = [[NSData alloc]initWithContentsOfFile:myStr];
[[self client] URLProtocol:self
didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:localdata];
[[self client] URLProtocolDidFinishLoading:self];
}else{
//
//不是需要更改的页面 则通过NSURLConnection去请求
//
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
}
//
//取消请求
//
- (void)stopLoading {
[self.connection cancel];
}
//
//#pragma mark - NSURLConnectionDelegate
//
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];;
//
//打印h5的代码
//
NSLog(@"%@",str);
[self.client URLProtocol:self didLoadData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.client URLProtocolDidFinishLoading:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self.client URLProtocol:self didFailWithError:error];
}
@end