how can I clear the contents of a UIWebView/WKWebView?

Halpo picture Halpo · Oct 20, 2015 · Viewed 18.6k times · Source

I have a webview that can be cycled through different URLs. When I switch from one to the other I want the old web page to disappear before loading the next one. How can I do this without re allocating the webview?

If I try to [self.webView loadHTMLString:@"" baseURL:nil]; and load my URL in the same function the previous web page still remains:

[self.webView loadHTMLString:@"" baseURL:nil];
[self.webView loadRequest:[NSURLRequest requestWithURL:self.pageURL]];

EDIT: this apparently isn't clear enough for you. the below code doesn't clear the webview, it displays the previous page until the new one is loaded:

- (void) startLoadOfNextURL:(NSURL*)url
{
    // clear:
    [self.webView loadHTMLString:@"" baseURL:nil]; //DOESNT WORK  

    // Load real next URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

Answer

Donal picture Donal · Feb 8, 2017

You can write below code while your controller dismiss.

webView.load(URLRequest(url: URL(string:"about:blank")!))