从应用程序的文档目录中加载本地HTML文件(Swift WKWebView)

3
我正在尝试使用wkwebview加载已下载到我的应用程序的本地html文件。除了这个html文件,我还下载了两个js文件,它们被引用在html文件中。但是无论我怎么做,它们都无法在wkwebview中加载。
 @IBOutlet var webView: WKWebView!
    @IBOutlet var act: UIActivityIndicatorView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Adding webView content
        webView.uiDelegate = self
        webView.navigationDelegate = self


let fm = FileManager.default
    let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let myurl = docsurl.appendingPathComponent("index.html")
    print("my url = ",myurl )
// myurl prints file///var/some directories/index.html
let request = URLRequest(url: myurl!)
            webView.load(request)
}

我的HTML文件

<!DOCTYPE html>
 <html> 
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

但是从Safari中无法加载到屏幕上(Develop/),我可以看到An error occurred trying to load the resource,页面显示为about:blank。


myurl会打印什么?你在这里如何使用 WKWebView - TheTiger
但它在Safari浏览器上无法加载到屏幕上(Develop/)。这是什么意思?Safari是一个外部浏览器。你的意思是只指WebView而不是Safari吗? - TheTiger
这段代码let request = URLRequest(url: myurl) self.webView.load(request)没有问题。您需要通过从该URL创建Data对象来检查是否存在相同的文件。 - TheTiger
@TheTiger,是的,在我的模拟器中它正常工作,但在 iPhone(真实设备)上无法正常工作。 - milsha
你的接受率是0。你没有接受任何一个答案来回答你的所有问题。这不好。 - TheTiger
2个回答

2

swift 4.2

 //load HTML
let bundle = Bundle.main
var path = bundle.path(forResource: "index", ofType: "html")
var html = ""
do {
    try html = String(contentsOfFile: path!, encoding: .utf8)
} catch {
//ERROR
}
let urlstr = "http://website.com"
webViewWK.loadHTMLString(html, baseURL: URL(string: urlstr)!)

2

URLRequest基本上是为了实时URL而设计的。对于系统文件,只需加载URL即可。您需要使用以下方法,它会起作用:

URLRequest用于实时URL,URL用于系统文件。

/*! @abstract Navigates to the requested file URL on the filesystem.
     @param URL The file URL to which to navigate.
     @param readAccessURL The URL to allow read access to.
     @discussion If readAccessURL references a single file, only that file may be loaded by WebKit.
     If readAccessURL references a directory, files inside that file may be loaded by WebKit.
     @result A new navigation for the given file URL.
     */
    @available(iOS 9.0, *)
    open func loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL: URL) -> WKNavigation?

So that:

self.webView.loadFileURL(myurl, allowingReadAccessTo: myurl)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接