I am loading a url in WKWebView.
let url = URL(string: "myURL")
let request = URLRequest(url: url!)
webView1.navigationDelegate = self as! WKNavigationDelegate
webView1.load(request)
But, the delegate function,
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(webView.url)")
}
not trigger when it complete load.
Then I use KVO for the web view
webView1.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "loading") {
guard var web1 = object as? WKWebView else { return }
}
}
Loading is working fine. But, is there any observer
available for after load the webview
A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.
Methods for accepting or rejecting navigation changes, and for tracking the progress of navigation requests.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
must called if you set navigationDelegate
properly.
Have you done this?
class ViewController: UIViewController, WKNavigationDelegate {
}
if you set the above WKNavigationDelegate
, your code will be like this,
let url = URL(string: "http://www.google.com")
let request = URLRequest(url: url!)
webView.navigationDelegate = self
webView.load(request)
and delegate method,
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url \(String(describing: webView.url))")
}
Hope this helps, let me know in case of any queries.
FYI. No need to set external observers.
UPDATE
Enable App Transport Security
in your info.plist
like this?
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With