Using WKWebkit in iOS – Simple Example

By | December 2, 2018

Whenever you want to show a webpage in your iOS App, use WKWebview instead of UIWebview. You have to supply an url that is complete. ie. with “http” or “https”. If you are using “http”, make sure you enable the “App Transport Security Settings” and add “Allow Arbitrary Loads” to yes.

 

 

Our Final output will look like this.

Init Webview

  func loadPage() {
        let url = URL(string: "http://coderzheaven.com")!
        self.webView.load(URLRequest(url: url))
        self.webView.allowsBackForwardNavigationGestures = true
  }

Listen to Navigation Events

We will have to add the Delegate class WKNavigationDelegate and implement it’s methods.

class ViewController: UIViewController, WKNavigationDelegate 

Implement the WKNavigationDelegate methods

First we will register for some events in the viewDidLoad like this

 func setWebviewObservers() -> Void {
    webView.navigationDelegate = self;
    let webViewKeyPathsToObserve = ["loading", "estimatedProgress"]
    for keyPath in webViewKeyPathsToObserve {
        webView.addObserver(self, forKeyPath: keyPath, options: .new, context: nil)
    }
}

call setWebviewObservers() in the viewDidLoad method.

Now we will implement the methods for us to listen to the webview events.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finished")
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Navigation Started...");
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(.allow)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let keyPath = keyPath else { return }
    switch keyPath {
        case "loading":
            print("loading")
            self.btnBack.isEnabled = webView.canGoBack
            self.btnFwd.isEnabled = webView.canGoForward
        case "estimatedProgress":
            let p = Int(webView.estimatedProgress * 100)
            if 100 == p {
                // Loading Complete
            }else{
               // Still Loading...
            }
            break;
        default:
            break
    }
}

Go Forward and Backward

Here I have two button for forward and backward navigation in your webView app.

webView.canGoForward will be true if the browser can move to the next page, similar to a web browser. webView.canGoBack will be true if the browser can move to the previous page, similar to a web browser.

@IBAction func btnTapFwd(_ sender: Any) {
    if webView.canGoForward {
        webView.goForward()
    }
}

@IBAction func btnTapBck(_ sender: Any) {
    if webView.canGoBack {
        webView.goBack()
    }
}

Thanks. Let me know if you have any comments.

Leave a Reply

Your email address will not be published. Required fields are marked *