iOS WKWebview实现拦截js,css,html以及图片资源替换为本地资源的两种方式(NSUrlProtocol)


NSURLProtocol简介

NSURLProtocol是URL Loading System的重要组成部分。它是一个抽象类。可以拦截网络请求。可以拦截的网络请求包括NSURLSession,NSURLConnection以及UIWebvIew。现也支持WKWebview框架,本文就是采用WKWebview。


方式

拦截做替换的方式有两种

  • 重定向到本地资源,利用canonicalRequestForRequest实现
  • 根据url,自定义response。

下面先说第一种实现方式:

1、无论哪种实现方式都必须注册NSURLProtocol

我这里在AppDelegate的didFinishLaunchingWithOptions方法里面进行注册,代码如下

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    //注册
    [NSURLProtocol registerClass:[BaseOnRedirectRequestURLProtocol class]];

    //实现拦截功能

    Class cls = NSClassFromString(@"WKBrowsingContextController");

    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");

    if([(id)clsrespondsToSelector:sel]) {
#pragma clang diagnostic push

#pragma clang diagnostic ignored"-Warc-performSelector-leaks"

        [(id)cls performSelector:sel withObject:@"myapp"];

#pragma clang diagnostic pop

    }

    return YES;

}
2、创建NSURLProtocol子类BaseOnRedirectRequestURLProtocol
  • 在.m文件中 遵循协议
  • 创建 NSURLSessionDataTask 对象
           @property (nonnull,strong) NSURLSessionDataTask *task;
  • 下面是NSURLSession代理方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [[self client] URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    [self.client URLProtocolDidFinishLoading:self];
}
3、准备就绪后,下面开始实现拦截功能
  • 注册NSURLProtocol后,客户端所有请求都将走+ (BOOL)canInitWithRequest:(NSURLRequest *)request。
    下面是代码片段:
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSLog(@"request.URL.absoluteString = %@",request.URL.absoluteString);
    NSString *scheme = [[request URL] scheme];
    if ( ([scheme caseInsensitiveCompare:@"http"]  == NSOrderedSame ||
          [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame ))
    {
        //看看是否已经处理过了,防止无限循环
        if ([NSURLProtocol propertyForKey:BaseOnRedirectRequestURLProtocolKey inRequest:request])
            return NO;
        return YES;
    }
    return NO;
}
  • request 重定向方法 下面代码中的地址,改为你需要拦截的地址,本地路径也改为你需要替换的本地资源
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    
    NSLog(@"url ---[%@]\n\n",request.URL.absoluteString);
    
    //request截取重定向
    if ([request.URL.absoluteString isEqualToString:@"http://xxx/xxx.js"])
    {
        NSString * filePath = [[NSBundle mainBundle] pathForResource:@"NewProject" ofType:@"js"];

        NSURL * url = [NSURL fileURLWithPath:filePath];
        mutableReqeust.URL = url;
        
        
    }
    return mutableReqeust;
}
  • 在startLoading中开始加载
- (void)startLoading{
    
    NSMutableURLRequest* request = self.request.mutableCopy;
    [NSURLProtocol setProperty:@YES forKey:BaseOnRedirectRequestURLProtocolKey inRequest:request];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    self.task = [session dataTaskWithRequest:self.request];
    [self.task resume];
    
}
  • stopLoading中记得销毁
- (void)stopLoading
{
    if (self.task != nil) {
        [self.task  cancel];
    }
}

至此第一种拦截替换本地资源的方式已实现,控制器加载WKWebView在本文末尾写

下面先说第二种实现方式:

1、首先同第一种方式,都需要注册
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    //注册
    [NSURLProtocol registerClass:[BaseOnResponseURLProtocol class]];

    //实现拦截功能

    Class cls = NSClassFromString(@"WKBrowsingContextController");

    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");

    if([(id)clsrespondsToSelector:sel]) {
#pragma clang diagnostic push

#pragma clang diagnostic ignored"-Warc-performSelector-leaks"

        [(id)cls performSelector:sel withObject:@"myapp"];

#pragma clang diagnostic pop

    }

    return YES;

}
2、创建NSURLProtocol子类BaseOnResponseURLProtocol
  • 在.m文件中 遵循协议
  • 创建 NSURLConnection 对象
           @property (nonatomic, strong) NSURLConnection *connection;
  • 下面是NSURLConnection代理方法
#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 {
    [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];
}
3、准备就绪后,下面开始实现拦截功能
  • 注册NSURLProtocol后,客户端所有请求都将走+ (BOOL)canInitWithRequest:(NSURLRequest *)request。
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSLog(@"request.URL.absoluteString = %@",request.URL.absoluteString);

    if ( ([request.URL.absoluteString hasPrefix:@"http://game.scool.online/cutcake1/"]))
    {
        //看看是否已经处理过了,防止无限循环
        if ([NSURLProtocol propertyForKey:BaseOnResponseURLProtocolKey inRequest:request]) {
            return NO;
        }
        
        return YES;
    }
    return NO;
}
  • 在startLoading中加载,实现思路:将需要替换的地址重新拼接response返回,再响应本地资源,代码如下:
- (void)startLoading {
 
    
    //1.获取资源文件路径 ajkyq/index.html
    NSURL *url = [self request].URL;
   
    //2.读取资源文件内容
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NewProject" ofType:@"js"];

    NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];
    NSData *data = [file readDataToEndOfFile];
    [file closeFile];

    //3.拼接响应Response
    NSInteger dataLength = data.length;
    NSString *mimeType = [self getMIMETypeWithCAPIAtFilePath:path];
    NSString *httpVersion = @"HTTP/1.1";
    NSHTTPURLResponse *response = nil;
    
    if (dataLength > 0) {
        response = [self jointResponseWithData:data dataLength:dataLength mimeType: mimeType requestUrl:url statusCode:200 httpVersion:httpVersion];
    } else {
        response = [self jointResponseWithData:[@"404" dataUsingEncoding:NSUTF8StringEncoding] dataLength:3 mimeType:mimeType requestUrl:url statusCode:404 httpVersion:httpVersion];
    }
    
    //4.响应
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
    
    
}
  • jointResponseWithData方法实现如下:
#pragma mark - 拼接响应Response
-(NSHTTPURLResponse *)jointResponseWithData:(NSData *)data dataLength:(NSInteger)dataLength mimeType:(NSString *)mimeType requestUrl:(NSURL *)requestUrl statusCode:(NSInteger)statusCode httpVersion:(NSString *)httpVersion
{
    NSDictionary *dict = @{@"Content-type":mimeType,
                           @"Content-length":[NSString stringWithFormat:@"%ld",dataLength]};
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:requestUrl statusCode:statusCode HTTPVersion:httpVersion headerFields:dict];
    return response;
}
  • MIMEType类型获取如下
#pragma mark - 获取mimeType
-(NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path
{
    if (![[[NSFileManager alloc] init] fileExistsAtPath:path]) {
        return @"text/html";
    }
    
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)(MIMEType);
}

至此第二种实现方式也已完成,下面贴上控制器中的代码

1、引用#import 和 #import "NSURLProtocol+WKWebVIew.h" 并遵循

NSURLProtocol+WKWebVIew 是对NSURLProtocol的一个扩展,主要是注册http和https协议,本文不做介绍,demo里会有的。

2、声明WKWebView对象

       @property (nonatomic) WKWebView* webView;

3、viewDidLoad中代码
- (void)viewDidLoad {
    [super viewDidLoad];
    [NSURLProtocol wk_registerScheme:@"http"];
    [NSURLProtocol wk_registerScheme:@"https"];
    [self.view addSubview:self.webView];
}
4、WKWebView懒加载
- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [WKUserContentController new];

        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 30.0;
        configuration.preferences = preferences;

        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        if ([_webView respondsToSelector:@selector(setNavigationDelegate:)]) {
            [_webView setNavigationDelegate:self];
        }

//        if ([_webView respondsToSelector:@selector(setDelegate:)]) {
            [_webView setUIDelegate:self];
//        }
        NSURL *url = [NSURL URLWithString:@"http://game.scool.online/cutcake1/"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:request];

    }
    return _webView;
}
5、别忘记回调哦
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    completionHandler();

}



拦截的两种方式都实现啦,有帮到你么?第一次写,希望给个小心心支持一下,如果能关注一下本仙女,那就确定你是好人无疑啦~

附上demo地址:https://github.com/yananSun/WKLoadResource.git

你可能感兴趣的:(iOS WKWebview实现拦截js,css,html以及图片资源替换为本地资源的两种方式(NSUrlProtocol))