Erez Hod
Erez Hod

Reputation: 1883

WKWebView does not load local html files

I have a WKWebView that works perfectly fine when given a URL or a URLRequest, but when I am trying to load local bundle html files into it, it just doesn't display anything.

I am trying it like so:

let webView = WKWebView()

if let bundleURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "mySubDirectory/v1") {
    webView.loadFileURL(bundleURL, allowingReadAccessTo: bundleURL.deletingLastPathComponent())
}

I have tested that the bundleURL actually returns the right path and tried copying + pasting it in my browser at run time and it works great: file:///Users/myuser/Library/Developer/Xcode/DerivedData/FireApp-gugmufgdkejtfdhglixebzhokhfe/Build/Products/Debug-iphonesimulator/SteppingIntoFireFramwork.framework/mySubDirectory/v1/index.html

What could be the problem?

Upvotes: 1

Views: 3862

Answers (4)

JozeRi
JozeRi

Reputation: 3429

If the URL works, then it seems that your webview is having trouble loading it.

I once had this issue... Check that you don’t have only “http” & “https” enabled for the allowed URL scheme

Upvotes: 2

whoover
whoover

Reputation: 89

Try to remove deletingLastPathComponent() from your example. Also you can try to use load(request) instead of loadFileURL().

if let bundleURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "mySubDirectory/v1") {
    let request = URLRequest(url: bundleURL)
    webView.load(request)
}    

Upvotes: 0

matt
matt

Reputation: 535140

Your web view is just a local temporary variable. It has zero size and is not in the interface, so you never see anything happen.

Upvotes: 0

ymutlu
ymutlu

Reputation: 6715

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = WKWebView()
        let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
        let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false)
        webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
        webView.navigationDelegate = self
        view = webView
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Full solution here

Upvotes: 0

Related Questions