WKWebView: Getting Started
A WKWebView is a subclass of UIView that is used to present web content inside the app UI. It can be used to present HTML, CSS, and JavaScript-based content alongside your app’s native UI
Since WKWebView
is part of WebKit
, we need to import it to our file using
import WebKit
Loading a website using WKWebView
The below code snippet loads “https://www.talkingwithswift.com” and sets that as the UIViewController
‘s view.
class ExampleViewController: UIViewController {
var webView: WKWebView!
// Other properties and functions
func loadWebview() {
webView = WKWebView()
let url = URL(string: "<https://www.talkingwithswift.com>")!
webView.load(URLRequest(url: url))
self.view = webView
}
}
In the first line, we create a WKWebView
object and store it in the webView
property of the ExampleViewController
Url is stored using a special type called URL in swift. Hence we create that object by passing the website’s URL as string to the initializer.
We use the load(_:)
method of WKWebView
to the website URL. This method takes an URLRequest
object as an argument, and hence we create URLRequest object using the URL which we have created in the previous line.
Finally, we set the viewcontroller’s view
to the created webView
Loading HTML using WKWebView
WKWebView
also allows loading local HTML file contents in your app. In this example, we try to load the index.html file, which is present in the app Bundle under the public directory. The public directory also contains the other assets, such as CSS
and JavaScript
files which are essential for loading the index.hml
func loadWebview() {
webView = WKWebView()
let htmlFileURL = Bundle.main.url(forResource: "index", withExtension:"html", subdirectory: "public", localization: nil)!
let parentURL = URL(string: (htmlFileURL.absoluteString as NSString).deletingLastPathComponent)!
webView.loadFileURL(htmlFileURL, allowingReadAccessTo: parentURL)
self.view = webView
}
As done previously, we create a WKWebView
object and store it in the webView
property of the ExampleViewController
In the second line, we try to get the URL
for the index.html
which is present in the Bundle
under the public directory.
In the third line, we try to get the URL
for the public directory using the htmlFileURL
. deletingLastPathComponent()
is a string method that removes the last path component and returns the path till the parent directory.
We use loadFileURL(_:allowingReadAccessTo:)
method to load the local file. We pass the htmlFileURL
as the first argument, and we give read access to parentURL
as the parent directory contains the necessary CSS
and JavaScript
files.
Finally, we set the viewcontroller’s view
to the created webView
So that’s the quick look and briefing about WKWebView
and its ways of loading HTML content.