I am very new to the whole programming business, and was wondering if there is any way to clear the contents of a UIWebView
in iphone programming, so that the l
Swift 4.0 , XCODE 9
webView.loadRequest(URLRequest.init(url: URL.init(string: "about:blank")!))
Try setting the URL to about:blank
and reload the page.
Just load an empty html string into it
[self.webView loadHTMLString:@"" baseURL:nil];
Swift, Xcode 7 beta 5
webView.loadRequest(NSURLRequest(URL: NSURL(string: "about:blank")!))
Answer extension for documentation purposes to maybe help someone else:
I had the same desire (clear content before loading next url) but had a UIWebView delegate set to receive webviewDidFinishLoad:(UIWebView)webview
message and update another part of UI in response.
Problem: the call to clear the content to also called delegate method, so getting false-hits (that is, getting call when clear is done, too, but delegate is coded to expect call only when real content is loaded).
Solution: use a known URL for clear, and have webviewDidFinishLoad:
ignore calls made when that URL is finished:
- (void) startLoadOfNextURL:(NSURL*)url
{
// clear:
[self.webView loadHTMLString:@"" baseURL:nil];
// Load real next URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"WebView finished loading: %@", webView);
if ([self.webView.request.URL.absoluteString isEqualToString:@"about:blank"]) {
NSLog(@" This is Blank. Ignoring as false event.");
}
else {
NSLog(@" This is a real url");
[self updateUIInSomeWay];
}
}
Note: using this:
[self.webView loadHTMLString:@"about:blank" baseURL:nil];
actually causes the words "about:blank" to appear as text in the webview's content pane!
Final complication: In practice, with my two [webview load...]
calls so close together, I was finding that instead of a "loaded" event for the clear, the webview was actually canceling it in favor of the second request and calling webView: didFailLoadWithError:
for the first load request. Thus, I had to put similar code in that event:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"WebView error on: %@", webView);
NSLog(@"Error is: %@", error);
NSURL* failingURL = [error.userInfo objectForKey:@"NSErrorFailingURLKey"];
if ([failingURL.absoluteString isEqualToString:@"about:blank"]) {
NSLog(@" This is Blank. Ignoring.");
}
else {
NSLog(@" This is a real URL.");
[self doSomethingAboutError];
}
}
Same answer in Swift 4.2, xCode 10
if let clearURL = URL(string: "about:blank") {
myWebView.loadRequest(URLRequest(url: clearURL))
}