WKWebView不会加载本地html文件

时间:2018-07-18 12:14:11

标签: ios swift wkwebview

我有一个WKWebView,当给定URLURLRequest时工作得很好,但是当我尝试将本地包html文件加载到其中时,它却没有显示任何内容。

我正在这样尝试:

let webView = WKWebView()

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

我已经测试过bundleURL实际上返回了正确的路径,并尝试在运行时将其复制并粘贴到浏览器中,并且效果很好: file:///Users/myuser/Library/Developer/Xcode/DerivedData/FireApp-gugmufgdkejtfdhglixebzhokhfe/Build/Products/Debug-iphonesimulator/SteppingIntoFireFramwork.framework/mySubDirectory/v1/index.html

可能是什么问题?

4 个答案:

答案 0 :(得分:4)

如果该URL有效,则表明您的Web视图无法加载它。

我曾经遇到过这个问题...检查您是否仅对允许的URL方案启用了“ http”和“ https”

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您的网络视图只是一个本地临时变量。它的大小为零,并且不在界面中,因此您永远不会看到任何事情。

答案 3 :(得分:0)

尝试从您的示例中删除deleteLastPathComponent()。 您也可以尝试使用load(request)代替loadFileURL()。

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