tda
tda

Reputation: 241

Switching from UIWebView to WKWebView Delegates

What would the equivalent of

webView.delegate = self

Be in a WKWebView? I have

webView2.UIDelegate = self

But it does not work as intended.

Upvotes: 1

Views: 1668

Answers (2)

Hanyoup Cho
Hanyoup Cho

Reputation: 95

You can monitor WKWebView's canGoBack and canGoForward, using key-value observing.

SWIFT 3

Add two key-value observers to WKWebView.

let webView = WKWebView(frame: view.frame)
view.addSubview(webView)

webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoBack), options: .new, context: nil)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoForward), options: .new, context: nil)

Now, implement observeValue(forKeyPath:) method in your view controller.

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if keyPath == #keyPath(WKWebView.canGoBack) || keyPath == #keyPath(WKWebView.canGoForward) {
        // Do Something...
    }
}

For example, you can add something like this to the change tint color of the buttons.

backButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray
forwardButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray

I found this method by reading an article from here.

https://www.hackingwithswift.com/example-code/wkwebview/how-to-monitor-wkwebview-page-load-progress-using-key-value-observing

Upvotes: 7

paulvs
paulvs

Reputation: 12053

Are you sure the only change to the code is changing UIWebView to WKWebView? I have made a sample project and the tap gesture recognizer worked for both UIWebView and WKWebView. Here is the relevant code:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: view.frame)
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        let urlString = "https://www.google.com"
        let url = NSURL(string: urlString)!
        let urlRequest = NSURLRequest(URL: url)
        webView.loadRequest(urlRequest)

        let recognizer = UITapGestureRecognizer(target: self, action: #selector(webViewTapped))
        recognizer.delegate = self
        webView.addGestureRecognizer(recognizer)
    }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

    func webViewTapped(recognizer: UITapGestureRecognizer) {
        print("Tapped")
    }
}

Upvotes: 0

Related Questions