How to Load local web files & resources in WKWebView
In Swift you can load HTML files into your WKWebView from an file which is part of your App Bundle. Before you use the below code snippet, please make sure that the HTML file you want to display in WKWebView is added to your project.
Load Local HTML File to a WKWebView
Step 1
Import the folder of local web files anywhere into your project. Make sure that you:
- Copy items if needed
- Create folder references (not “Create groups”)
- Add to targets
Step 2
Go to the View Controller with the WKWebView and add the following code to the viewDidLoad method:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
index – the name of the file to load (without the .html extension)
website – the name of your web folder (index.html should be at the root of this directory)
Conclusion
The overall code should look something like this:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "Website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.