How to Load local web files & resources in WKWebView

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)

    }

}

tips & tricks

Join 7,719 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps blogging Browser CheatSheets Code Config CSS DATABASE dsa error Features HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Placeholder Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading