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

How to control the sites a WKWebView can visit using WKNavigationDelegate

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.

Learn Server-Side Swift now!

Take your Swift code to the server and become a full-stack developer with my latest book: Server-Side Swift!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.0/5

Click here to visit the Hacking with Swift store >>