Gianfranco Lemmo Gianfranco Lemmo - 1 year ago 260
iOS Question

WKWebView get the old value Scroll Height after rotate the phone iOS9

I have the WKWebView inside a cell, but the problem is When rotated the phone, I get the old value of the WkWebView Scroll Height, For that reason the content don't load completly.

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
self.contentHeights[3] = self.webView.scrollView.contentSize.height

This method change the height of the row of the table cell but the value I get is before at to be rotated.

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
if indexPath.row == 3{
return contentHeights[indexPath.row]
contentHeights[indexPath.row] = UITableViewAutomaticDimension
return contentHeights[indexPath.row]

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 3{
return contentHeights[indexPath.row]
return UITableViewAutomaticDimension

The row 3 is the WkWebView Any Help???

Answer Source

I read several post after that I founded two way to resolve the problem.

First I used KVO

addObserver(self, forKeyPath: "webView.scrollView.contentSize", options: .New, context: nil)

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "webView.scrollView.contentSize" {
    if let nsSize = change[NSKeyValueChangeNewKey] as? NSValue {
        let height = nsSize.CGSizeValue().height
        // Do something here using content height.

removeObserver(self, forKeyPath: "webView.scrollView.contentSize", context: nil)

The second way is a event on Javascript:

Add the following code to html code:

<script>$(document).ready(function(){$( document ).resize(function() {webkit.messageHandlers.callbackHandler.postMessage($( document ).height())});});</script>

Add the WkWebView the following configuration:

var contentController:WKUserContentController!
override func loadView() {
    contentController = WKUserContentController()
        name: "callbackHandler"

    config = WKWebViewConfiguration()
    config.userContentController = contentController
    self.webView = WKWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height), configuration: config)

Add the following function:

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {  
    if( == "callbackHandler") {
        if !positionOrientationLanscape{
            sizeLanscape = CGFloat((message.body as! NSNumber).doubleValue)
            contentHeights[4] = sizeLanscape
            sizePortrait = CGFloat((message.body as! NSNumber).doubleValue)
            contentHeights[4] = sizePortrait

Don't forget deinit

deinit {