Load HTML To WebView

WebView is very powerful and dangerous at the same time. It can display complex HTML such as a response from the request or prepared before some websites. It is also very important that web views might open security vulnerabilities.

Last time we showed HTML in UITextView this time let’s show some HTML in a web view. HTML will be from the Internet (web), local file and string in code.

Firstly:

import WebKit

Next, create an instance of WKWebView.

let webView = WKWebView()

In this example to make it cleaner replace default view by webView.
Inside viewDidLoad:

view = webView

Load data from the Internet:

if let url = URL(string: “https://smashswift.com”) {
    let urlRequest = URLRequest(url: url)
    webView.load(urlRequest)
}

Result:

WebView With URL

Load data from local file:

if let filePath = Bundle.main.url(forResource: “web”, withExtension: “html”) {
    let urlRequest = URLRequest(url: filePath)
    webView.load(urlRequest)
}

File web.html has to exist in your project.

Result:

WebView With Local HTML

Last case, load data from string in code:

let html = “<!DOCTYPE html><html><body><h1>Hello SmashSwift!</h1></body></html>”
webView.
loadHTMLString(html, baseURL: nil)

Result:

WebView With Local HTML

Yes, HTML is the local file that is the same as in HTML variable.