Search code examples
iosobjective-cwkwebview

Disable loading images in WKWebView ios


I am creating an app, in which supremenewyork.com website is loaded in WKWebView. But when the website is loaded I do not want to load images in it. How can I do this in Objective-C.


Solution

  • I have following which prevent to load images of website in WKWebView. I have used content blocker rules which are documented official web site of Apple. Check here. Creating a Content Blocker.

    - (void)viewDidLoad {
        [super viewDidLoad];
    
    //    id blockRules = @" [{ \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"image\"] }, \"action\": { \"type\": \"block\" } }, { \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"style-sheet\"]          }, \"action\": { \"type\": \"block\" } }, { \"trigger\": { \"url-filter\": \".*.jpeg\" }, \"action\": {              \"type\": \"ignore-previous-rules\" } }] ";
    
        id blockRules = @" [{ \"trigger\": { \"url-filter\": \".*\", \"resource-type\": [\"image\"] }, \"action\": { \"type\": \"block\" } }] ";
    
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.supremenewyork.com/"]];
    
        [[WKContentRuleListStore defaultStore] compileContentRuleListForIdentifier: @"ContentBlockingRules" encodedContentRuleList:blockRules completionHandler:^(WKContentRuleList *contentRuleList, NSError *error) {
    
            if (error != nil) {
                NSLog(@"Error = %@", error.localizedDescription);
            }
            else {
                WKWebViewConfiguration *configuration = self.webView.configuration;
                [[configuration userContentController] addContentRuleList:contentRuleList];
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.webView loadRequest:request];
                });
            }
        }];
    }
    

    Output: 1. Disable Image Load 1

    Output: 2. Disable Image Load 2