Web View iOS Tutorial

In this tutorial a web browser is created using the WKWebView object.  A website will be loaded, where the title will be displayed and a refresh button will be added to the toolbar. This tutorial is made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11WebViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and select the View Controller. Go to the Editor menu and select Embed in -> Navigation Controller.

Go to the ViewController.swift file and import the WebKit module.

import WebKit

Add the webView property to the ViewController class

var webView: WKWebView!

Change the class declaration to implement the WKNavigationDelegate protocol. 

class ViewController: UIViewController, WKNavigationDelegate {

Add the loadView method

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

The WKWebview is assigned to the root view and the view controller is a delegate of the WKNavigationDelegate protocol. Change the viewDidLoad method to

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 1
    let url = URL(string: "https://ioscreator.com")!
    webView.load(URLRequest(url: url))
      
    // 2  
    let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
    toolbarItems = [refresh]
    navigationController?.isToolbarHidden = false
}
  1.  The webView loads the url using an URLRequest object.
  2. a refresh item is added to the toolbar which will refresh the current webpage.

Next, Implement the webView(_:didFinish:) delegate method

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

The title of the webpage will be displayed in the title bar when the website is loaded.

Build and Run the project.

You can download the source code of the IOS11Tutorial at the ioscreator repository on Github.