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文件中 遵循協議<NSURLSessionDelegate>
  • 創建 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文件中 遵循協議<NSURLConnectionDelegate>
  • 創建 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 <WebKit/WebKit.h> 和 #import "NSURLProtocol+WKWebVIew.h" 并遵循<WKNavigationDelegate,WKUIDelegate>

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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容