Let’s learn how to implement WKWebView in Your iOS, iPadOS and macOS Catalyst app

Before we jump into implementing WKWebView I would first introduce you to why you want to use it. WKWebView helps you when you want to load a webpage inside your app without throwing users to a third party browser outside of your app.

Let’s start coding,

Step 01: First Import WebKit

import WebKit

Step 02: Add ‘WKNavigationDelegate’ to your declaration of ViewController Class

WKNavigationDelegate

It will look something like this:

class ViewController: UIViewController, WKNavigationDelegate {
}

Step 03: Now create two variables for loading webView and one for button which will close webView

var webView: WKWebView!
var closeWebViewUIButton = UIButton(type: .system) as UIButton

Step 04: Now naviagte to your ViewDid Load method

override func viewDidLoad() {
super.viewDidLoad()
}

Step 05: Now in your ViewDidLoad method add the following code, Which will load WKWebView. You can change the URL as per your preference.

// Load the WebView
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
let url = URL(string: "https://www.google.com/")
webView.load(URLRequest(url: url!))
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
self.view.addSubview(webView)

Step 06: Now in your ViewDidLoad method add the following code, Which will load UIButton and work as a button to dismiss WKWebView.

// Load the closeWebViewUIButton
let config = UIImage.SymbolConfiguration(pointSize: 64, weight: .medium, scale: .large)
let image = UIImage(systemName: "xmark.square.fill", withConfiguration: config) as UIImage?
closeWebViewUIButton.frame = CGRect(x: self.view.bounds.width - 100, y: 0, width: 100, height: 100)
closeWebViewUIButton.setImage(image, for: .normal)
closeWebViewUIButton.addTarget(self, action: #selector(self.closeUIButtonTapped(sender:)), for: .touchUpInside)
self.view.addSubview(closeWebViewUIButton)

Step 07: Now add the following function inside your ViewController, Which will load UIButton and work as a button to dismiss WKWebView.

@objc func closeUIButtonTapped(sender:UIButton) {
webView.removeFromSuperview()
closeWebViewUIButton.removeFromSuperview()
}

I hope this information helps you to build your WebView,

Thanks & Regards
Mandar Apte

Mandar Apte

This website contains a design articles blog by Mandar Apte. He writes and shares his iOS development, graphic, web, & animation film design experience through articles. Mandar is Mumbai based multi-disciplinary designer with expertise in UI, UX, Logo, Symbol, and Brand Identity design. He is an alumnus of Sir J. J. Institute of Applied Art, Mumbai. He currently runs his studio in the heart of the city of Mumbai.

Leave a Reply

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