Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView memory leaks. What is the magic to release unused resources?

Although there are many discussions about the subject, I have not still found an answer.

The problem is, that after the UIWebView loads a page, it will never release all the used memory resources.

I have created an empty project. Just added the UIWebView. The memory used before loading a request (http://methodhome.com/cleanhappy) was 4.5MB, and after loading has completed - 70 ~ 90 MB.

After releasing the UIWebView, the used memory was still 55MB.

So it looks like there are about 50MB of leaked memory.

I have tried next methods:

[_webView stringByEvaluatingJavaScriptFromString:@"var body=document.getElementsByTagName('body')[0];body.style.backgroundColor=(body.style.backgroundColor=='')?'white':'';"];
[_webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML='';"];
[_webView stringByEvaluatingJavaScriptFromString:@"document.open();document.close();"];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
[_webView loadHTMLString:@"" baseURL:nil];
[_webView stopLoading];
_webView.delegate = nil;
[_webView removeFromSuperview];
_webView = nil;

[[NSURLCache sharedURLCache] removeAllCachedResponses];

I have also tried setting:

[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];

and have played with cache settings of memory and disk. Nothing helped.

How can it be possible? How are the popular browsers are working like Safari and Chrome with such a leaks. What is the trick to release those resources?

like image 640
Nikita Avatar asked Jan 12 '15 09:01

Nikita


1 Answers

How can it be possible?

UIWebView is an old API, based on WebKitLegacy. It's not deprecated for 1 single reason - Apple had no replacement (until iOS 9).

How are the popular browsers are working like Safari and Chrome with such a leaks.

Safari is a browser, created by Apple itself. It can use any hacks and private APIs, restricted in AppStore. Actually, for now Safari behavior is very close to WKWebView's one. But it never was similar to UIWebView.

Only recently Google Chrome was able to migrate to WKWebView. See https://bugs.chromium.org/p/chromium/issues/detail?id=423444 for details. Before that, Google Chrome was facing the same problem.

What is the trick to release those resources?

I've tried a lot of tricks, but none of them worked for me. Unfortunately, the only solution is migration to WKWebView, introduced in iOS 8. Moreover, WKWebView had a lot of bugs under iOS 8, so in most cases it's usable only starting from iOS 9.

like image 189
Borys Verebskyi Avatar answered Sep 27 '22 18:09

Borys Verebskyi