Modify an image in the webView

When we use a webView to load an interface, but there is an image icon in the webView that we do not want, we want to remove it or modify it.

methods

Create a new class that inherits NSURLProtocol @Interface QLWebURLProtocol: NSURLProtocol

Protocol implementation method:

@implementation QLWebURLProtocol + (BOOL)canInitWithRequest:(NSURLRequest *)request {/* prevents an infinite loop, because a request is intercepted and a request is also initiated, which would lead to an infinite loop if it is not processed */ /if ([NSURLProtocol propertyForKey:protocolKey inRequest:request]) {
//        return NO;
//    }
    NSString * url = request.URL.absoluteString;
    NSLog(@"% @",url); // If you want to block any loaded links, return YES. Default NOif ([request.URL.absoluteString isEqualToString:@"https://www.baidu.com"]) {
        return YES;
    }else {
        returnNO; } // Check whether the resource to be loaded exists locally //if ([QLWebURLProtocol localResourceIsExistWith:request]) {
//        return YES;
//    } else {
//        returnNO; / / / /}returnNO; } / / method 2 + (NSURLRequest *) canonicalRequestForRequest: (theRequest NSURLRequest *) {returntheRequest; } - (void)startLoading {// Get the URL you intercepted and do what you want. This URL may be disallowed or replaced with another URL. NSArray *myUrlArr = [[self class] myUrls]; NSArray *myUrlArr = [[self class] myUrls]; // NSInteger index = [myUrlArr indexOfObject:self.request.URL.absoluteString]; // NSString *imageName = [[[self class] myImageName] objectAtIndex:index]; // // NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL] // MIMEType:@"image/png"
//                                           expectedContentLength:-1
//                                                textEncodingName:nil];
//    NSArray *com = [imageName componentsSeparatedByString:@"."]; // NSString *imagePath = [[NSBundle mainBundle] pathForResource:com[0] ofType:com[1]]; // NSData *data = [NSData dataWithContentsOfFile:imagePath]; // // [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; // [[self client] URLProtocol:self didLoadData:data]; // [[self client] URLProtocolDidFinishLoading:self]; } - (void)stopLoading {NSLog(@)"something went wrong!");
}
Copy the code

// Private method to determine if there is something to replace

+ (BOOL)localResourceIsExistWith:(NSURLRequest *)request
{
    NSArray *arr = [self myUrls];
    if ([arr containsObject:request.URL.absoluteString]) {
        return YES;
    }
    returnNO; } // Replace the original webView link + (NSArray*)myUrls {return@ [@"https://uidesign.gbtcdn.com/check_out/paypal.png?impolicy==true"The @"https://uidesign.gbtcdn.com/check_out/money.png?impolicy=hight"The @"https://icss1.gearbest.com/imagecache/GB2/images/domeimg/pay_method/spp1.jpg"The @"https://uidesign.gbtcdn.com/check_out/poli.png?impolicy=high"The @"https://cashier.gearbest.com/static/img/mcredit.png"]; } // my own local image + (NSArray*)myImageName {return@ [@"paypal.png"The @"money.png"The @"spp1.jpg"The @"poli.png"The @"mcredit.png"];
}
Copy the code

Method of use

Register in your webView method class initialization, unregister in the Dealloc method.

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, Typically, NSURLProtocol registerClass:[QLWebURLProtocol class]]; [self.view addSubview:self.webView]; [self. WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
}
Copy the code

Then you can get all the requests to load Baidu:

Take removing baidu logo as an example: we can find baidu logo picture link

    if ([request.URL.absoluteString isEqualToString:@"https://m.baidu.com/static/index/plus/plus_logo.png"]) {
        return YES;
    }else {
        return NO;
    }
Copy the code

The startLoading method does not do any processing, and the Baidu logo is removed when running.

- (void)dealloc {[NSURLProtocol unregisterClass:[QLWebURLProtocol class]]; }Copy the code

The above method can be used to modify an image in the webView. Of course, you can also intercept the specified URL and do whatever you want. WKWebView does not seem to apply. I haven’t implemented it yet. Also ask the guidance of the great god.

UIWebView has been deprecated since iOS 12, and now you get a warning when you write a webVIew. So this doesn’t make a lot of sense, because you don’t use webViews much anymore. 🙂 (smile)