WKWebView iOS Tutorial

Hi, In today’s post, we’ll learn how to use WKWebView or simply saying, how to implement web view in iOS applications. I am using Xcode 9 and Swift 4 for this tutorial. So, let’s do it using our step by step approach:

STEP 1:

Open Xcode and create a Single View Application.
Give some name to your app, eg. WebViewAppTutorial and make sure to choose Swift as the language, click Next.

STEP 2:

Here, first we’ll embed our app in a navigator controller. For this, just open your Main.storyboard and click on View Controller. Now, select Editor from Xcode Menu bar, and select Embed in > Navigation Controller.

STEP 3:

Now, open ViewController.swift file and import webkit module.

import WebKit

Under your ViewController class , add the webView property as:

var webView: WKWebView!

Now, in your class declaration, add one WKNavigationDelegate protocol as shown below:

class ViewController: UIViewController, WKNavigationDelegate {

STEP 4:

Add loadView() method in your View Controller:

    override func loadView() {
        webView = WKWebView()
webView.navigationDelegate = self
        view = webView
    }

Now, in viewDidLoad() method, add following lines of code:

    override func viewDidLoad() {
super.viewDidLoad()
//Add your web URL here that you want to show in app screen.
            let url = URL(string: “https://www.brewit9.com”)!
            webView.load(URLRequest(url: url))
// Add this to reload the web page using a item in the tool bar
            let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
            toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
    }

Now, Implement webView(:didFinish:) method:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        title = webView.title
    }

This will add the website’s title on the title bar when your website will be loaded in the app.

That’s it, you can now run the app and web page will be displayed in the app instantly.

UPDATE: Please note that, if your given URL (Line number: 26 ) is not having a secure connection means it uses http:// instead of https://, then your webpage won’t load up in the iPhone and will give you an error something like “App transport security has blocked a..”. So, to avoid this, we need to follow these steps:

  • Go To Info.plist
  • Click on + sign here

  • Enter App Transport Security Settings
  • Click on arrow sign and then + sign
  • Now, write Allow Arbitrary Loads and change its value from NO to YES
That’s it. After following above steps, just run your app and it won’t give any error even with http:// URLs. 
 
Here’s full code for your reference:


If you’ve any doubts or need any further help, then do message me in the comments section below and I’ll try to respond you as soon as possible.

Thanks for your time and keep coding.. 👨‍💻