Darx Darx - 7 months ago 312
Swift Question

WKWebView Content loaded function never get called

i try to get a function called after my Content inside WKWebView is fully loaded. I found the "didFinishNavigation" function at the Apple Swift WKNavigation Documentation.

func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}


But the function never get called.

import UIKit
import WebKit

class ViewController: UIViewController WKNavigationDelegate {

override func loadView() {
super.loadView()

self.webView = WKWebView(frame:self.containerView.frame, configuration: WKWebViewConfiguration())
self.containerView.addSubview(webView!)
self.containerView.clipsToBounds = true

}

override func viewDidLoad() {
super.viewDidLoad()

var url = NSURL(string:"http://google.com/")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}

func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
println("WebView content loaded.")
}

}

Answer

You are not setting the navigationDelegate. Set it and it should be fine.

class ViewController: UIViewController, WKNavigationDelegate {


  override func viewDidLoad() {
    super.viewDidLoad()

    let noLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0)

    let webView = WKWebView(frame: CGRectZero, configuration: WKWebViewConfiguration())
    webView.setTranslatesAutoresizingMaskIntoConstraints(false)
    webView.navigationDelegate = self
    view.addSubview(webView)

    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))

    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: noLayoutFormatOptions, metrics: nil, views: ["webView": webView]))

    let url = NSURL(string: "http://google.com")
    let request = NSURLRequest(URL: url)
    webView.loadRequest(request)
  }

  func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
    println("Finished navigating to url \(webView.url)")
  }

}
Comments