WkWebView instances and memory leak

Viewed 2797

I wonder if there is a way to reduce or reuse instances of a wkwebview, since every time a method is implemented on a wkwebview

wkWebView.load(myRequest)

a web instance is generated and remains in memory, and I can see them all while debugging with Safari:

enter image description here

Every time the same page is shown, the memory consumption increases:

enter image description here

Loading "about: blank" does not solve the problem, as well as wkWebView = nil.

1 Answers

After some research, I found my mistake:

let webConfig = WKWebViewConfiguration()
let userController:WKUserContentController = WKUserContentController()
userController.add(self, name: "interOp")

In viewDidLoad was causing memory leak, since that userController was never been released (and for the wkwebview, too).

My solution is: declare the WKUserContentController in the class of the viewController containing the wkWebView:

var userController: WKUserContentController  = WKUserContentController()

reference to it in viewDidLoad:

userController.add(self, name: "interOp")
webConfig.userContentController = userController;

and release it in viewWillDisappear:

userController.removeScriptMessageHandler(forName: "interOp")

Maybe it is not the better way to manage this problem, but it works. When the view will be dismissed, it leave nothing in Safari and release his memory occupation:

enter image description here

Related