Introduction to WKWebView
In this tutorial, we will learn how to load web URL using WKWebView in swift language. WKWebView comes into existence in iOS 8.0, when Apple deprecated UIWebView and as a replacement launches new framework known as WebKit which contains WKWebView to allow developers to load web page url’s inside their apps. WKWebView is somewhat similar to UIWebView but is more enhanced and powerful than UIWebView.
Advantages of using WKWebView
- WKWebView runs on separate thread, this means separate memory is allocated to WKWebView, thus if WKWebView exceeds its memory then it only crash webview but not the app.
- WKWebView uses latest javascript engine and thus render the page faster as compared to older UIWebView javascript engine.
There are many more advantages of WKWebView but above two are important one in perspective of app developer.
How to load url using WKWebView in swift
Step 1: Create a single View application template project and name it “WKWEbView-Demo”. Open ViewController.swift.
Step 2: Import WebKit framework on top of your class declaration, and create two IBOutlet’s for
1) WKWebView :- loads our web page
2) UIActivityIndicatorView: Show activity indicator when our web page is loading and gets hidden once webview finish loading web page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// WKWEbView-Demo | |
// | |
// Created by iosTutorialJunction.com on 10/08/18. | |
// Copyright © 2018 iosTutorialJunction.com. All rights reserved. | |
// | |
import UIKit | |
import WebKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var webView: WKWebView! | |
@IBOutlet weak var activityIndicator: UIActivityIndicatorView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} |
Step 3: Open Main.storyboard file, and drag “Web Kit View” and UIActiVityIndicatorView to View-controller’s view. Add constraints to webview and activity indicator as shown in below images.
WKWebView Constraints: All four (top, leading, trailing, bottom) sets to zero i.e. with respect to safe area.
UIActivityIndicatorView Constraints: Aligned centered (vertically and horizontally) with respect to super view.
Step 4: Connect IBOutlets created in step 2 to respective controls i.e. web view and activity indicator view.
Step 5: Open ViewController.swift file and lets start loading webpage to our WKWebView using swift. Inside our viewDidLoad function add following source code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
activityIndicator.startAnimating() | |
activityIndicator.hidesWhenStopped = true | |
let urlString = "http://www.apple.com" | |
let request = URLRequest(url: URL(string: urlString)!) | |
self.webView.load(request) | |
} |
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
After adding keys to info.plist, run the app again and you will see web page, i.e. apple website gets loaded but activity indicator is still animating. WKWebView does not offer delegate methods like UIWebView does to let app knows that when weview starts loading the page and when webview stops loading. To solve this problem, we need to take use of isLoading property which a KVO compliant in WKWebView, it means that its isLoading is a KVO property and will transmit notification whenever the value of isLoading property of WKWebView gets changed,
Detect WKWebView start and stop loading events for url or web page
If we want to detect start and stop events of WKWebView, then we have to add our class where WKWebView is declared as key value observer for WKWebView property isLoading. Below is the code that shows how to add a class as an observer for KVO compliant property. Inside viewDidLoad function add below line code just above the closing brace of our viewDidLoad function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil) |
Implementing NSKeyValueObserving function
Lastly, we need to implement key value observing function so that when ever isLoading property of WKWebView chnages we get the callback in this function and perform our desired actions. Below is the code to start activityindicator when page starts loading and hide when webview stops loading.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
if keyPath == "loading" { | |
if webView.isLoading { | |
activityIndicator.startAnimating() | |
activityIndicator.isHidden = false | |
} else { | |
activityIndicator.stopAnimating() | |
} | |
} | |
} |
Where to go from here
In this tutorial, we learned about WKWebView replacement of UIWebView and how to load a we page url in ios application development using WKWebView or we can say that how to load web page using WKWebView . Also we learned how to use KVO property isLoading of WKWebView to detect loading events for WKWebView.