NEW: Master Swift design patterns with my latest book! >>

How to control the sites a WKWebView can visit using WKNavigationDelegate

Written by Paul Hudson    @twostraws

By default a WKWebView can navigate to any links the user selects, but it’s common to want to restrict that. It only takes a few simple steps:

  1. Make your view controller conform to WKNavigationDelegate.
  2. Assign your view controller to be your web view’s navigationDelegate.
  3. Implement the decidePolicyFor method to decide whether each URL should be allowed or denied.

Let’s try it out now. First, make your view controller conform to WKNavigationDelegate like this:

class ViewController: UIViewController, WKNavigationDelegate {

Second, set your view controller to be the navigationDelegate property of your web view:

webView.navigationDelegate = self

Finally, implement the decidePolicyFor method. This is the only part that takes any work: you need to pull out the host of the URL that was requested, run any checks you want to make sure it’s OK, then call the decisionHandler() closure with either .allow to allow the URL or .cancel to deny access.

Here’s an example to get you started:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if let host = navigationAction.request.url?.host {
        if host.contains("hackingwithswift.com") {
            decisionHandler(.allow)
            return
        }
    }

    decisionHandler(.cancel)
}

Available from iOS 9.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Go from iOS to macOS the easy way!

If you like Hacking with Swift, you'll love Hacking with macOS – learn to build macOS apps today, using 18 real-world projects!

Click here to visit the Hacking with Swift store >>