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.


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 With URL

Load data from local file:

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

File web.html has to exist in your project.


WebView With Local HTML

Last case, load data from string in code:

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


WebView With Local HTML

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