Search code examples
iosswiftwkwebview

Getting the link URL tapped in WKWebView


I want to get the url of a tapped link in WKWebView. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom. I am using KVO like so:

override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }

This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!


Solution

  • Change addObserver like this

    webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)
    

    In observeValue function you able get both value

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] as? Int, let oldValue = change?[.oldKey] as? Int, newValue != oldValue {
            //Value Changed
            print(change?[.newKey])
        }else{
            //Value not Changed
            print(change?[.oldKey])
        }
    }