Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView didFinish is not working Swift 4

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

like image 904
Vineesh TP Avatar asked Mar 26 '18 04:03

Vineesh TP


People also ask

What is WKWebView?

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.

What is Wknavigationdelegate?

Methods for accepting or rejecting navigation changes, and for tracking the progress of navigation requests.


1 Answers

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>
like image 133
PPL Avatar answered Oct 23 '22 04:10

PPL