Setting up WKWebView

August 22, 2019 ยท 1 minute read

So why do I need to use WKWebView, I don’t know - I just wanted to figure out something or another since I could.

So the easiest way to figure it out and set it up is programmatically. Period. Full stop. No IBOutlets unless you are glutton for punishment. Fill out the baseURL with whatever URL you want, but you can figure it out looking at Apple’s documentation.

  1. Add the library to your view controller: import WebKit
  2. Add this protocol to your class: WKUIDelegate
  3. Add “Exception Domains” under “App Transport Security Settings”. And then add under that “NSExceptionAllowsInsecureHTTPLoads” and “NSIncludesSubdomains”: Info List
  4. Setup as follows and adjust as need:
import UIKit 
import WebKit 

class MyViewController : UIViewController, WKUIDelegate
{
    var webView: WKWebView!
    var html: String = """
    
    // Add some html here
    
    """
    override func loadView()
    {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        self.view = webView
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        webView.loadHTMLString(html, baseURL: nil)
    }
}

Subscribe to my email list for a monthly newsletter and special updates!