美文网首页
WKWebView网页加载拦截并替换资源

WKWebView网页加载拦截并替换资源

作者: 搬运工开发者 | 来源:发表于2019-03-27 14:39 被阅读0次

    1.H5加载页面缓慢,考虑使用离线化加载。 确保[低速网络]或[无网络]可网页秒开。
    2.使用[NSURLProtocol]拦截 区别于uiwebview wkwebview使用如下方法拦截

    [NSURLProtocol registerClass:[MyCustomProtocol class]];
        Class cls = NSClassFromString(@"WKBrowsingContextController");
        SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
        if ([(id)cls respondsToSelector:sel]) {
            [(id)cls performSelector:sel withObject:@"http"];
            [(id)cls performSelector:sel withObject:@"https"];
        }
    

    MyCustomProtocol.h

    #import <Foundation/Foundation.h>
    
    @interface MyCustomProtocol : NSURLProtocol
    @end
    

    MyCustomProtocol.m

    + (BOOL)canInitWithRequest:(NSURLRequest *)theRequest {
        if ([theRequest.URL.absoluteString containsString:@"https://www.baidu.com/img/login_2d2c57b59121dec81f374c4fe080e9d3.png"]) {
            return YES;
        }
        return NO;
    }
    
    + (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)theRequest {
        return theRequest;
    }
    
    - (void)startLoading {
        NSMutableURLRequest* request = self.request.mutableCopy;
        NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
                                                            MIMEType:@"image/png"
                                               expectedContentLength:-1
                                                    textEncodingName:nil];
        
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
        NSData *data = [NSData dataWithContentsOfFile:imagePath];
        
        [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        [[self client] URLProtocol:self didLoadData:data];
        [[self client] URLProtocolDidFinishLoading:self];
        NSLog(@"start loading !");
        
    }
    
    - (void)stopLoading {
        NSLog(@"something went wrong!");
    }
    

    3、使用

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        [NSURLProtocol registerClass:[MyCustomProtocol class]];
        Class cls = NSClassFromString(@"WKBrowsingContextController");
        SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
        if ([(id)cls respondsToSelector:sel]) {
            [(id)cls performSelector:sel withObject:@"http"];
            [(id)cls performSelector:sel withObject:@"https"];
        }
        
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
        [self.view addSubview:self.webView];
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
    }
    

    相关文章

      网友评论

          本文标题:WKWebView网页加载拦截并替换资源

          本文链接:https://www.haomeiwen.com/subject/dwyzvqtx.html