FREE: Watch my new YouTube videos, Xcode in 20 Seconds! >>

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.

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

yourWebView.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)
}

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!

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.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns 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 Advanced iOS Volume Two 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 >>