Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView goes blank after memory warning

Tags:

ios

wkwebview

I'm developing an iOS app that will show some 360 panoramic content in a wkWebView. The page does load, but when it receives a memory warning, it shows a blank view on iPad 2.

Relevant code:

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://360yerevan.com/mobilembed/91001/"] ];


NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
wkWebConfig.processPool = [[WKProcessPool alloc] init];

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];

[self.view addSubview:webView];
[webView loadRequest:req];

This works fine on iPhone 5/5S.

Any thoughts?

like image 773
Asatur Galstyan Avatar asked Dec 19 '14 11:12

Asatur Galstyan


1 Answers

One major cause of this is the WebContent process crashing.

In iOS 9 and above you can use the WKNavigationDelegate method webViewWebContentProcessDidTerminate to catch this case. It's up to you to decide how to respond to the crash, but if reloading the page is enough, then [webView reload] will do the trick as shown below. As @ray mentions in the comments, you will not get any useful information about the why of the crash from this delegate call.

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    // Reload current page, since we have crashed the WebContent process
    // (most likely due to memory pressure)
    [webView reload];
}

In iOS8 and below, you can check if myWKWebViewInstance.title is nil.

like image 75
Maple Avatar answered Oct 20 '22 16:10

Maple