Swift 3 - WKWebView 加载本地 HTML 不加载资源文件 [英] Swift 3 - WKWebView Load Local HTML not loading resource files

查看:68
本文介绍了Swift 3 - WKWebView 加载本地 HTML 不加载资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从网上下载我的网站并存储在带有子文件夹的 xcode 项目中,并希望在本地运行 WKWebView.我发现 webview 加载的网页缺少所有 CSS/JS/Images 资源.我在互联网上搜索,但仍然无法正常工作.相对 url 中的网页是不正确的还是我的代码来获取 Main Bundle 位置问题?任何人都可以提供帮助.谢谢.

I was download my website from online to store in xcode project with a sub-folder and want to run in WKWebView locally. I found the webview loaded webpage miss all CSS/JS/Images resources. I search around the internet and still not working. Is webpage inside relative url incorrect or my code to get the Main Bundle location problem? Anyone can help. Thanks.

Xcode 项目结构

HTML 页面内容示例

我写了这段代码来加载 WKWebView

I wrote this code to load WKWebView

let htmlFile = Bundle.main.path(forResource: "provisiontech", ofType: "htm")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
let baseURL = Bundle.main.resourceURL!.appendingPathComponent("pvtc")
webView.loadHTMLString(html!, baseURL: baseURL)

推荐答案

webview 无法访问资源文件夹.您应该改用 loadFileURL(_:allowingReadAccessTo:).不需要预加载数据,例如:

The webview has no access to the resource folder. You should use loadFileURL(_:allowingReadAccessTo:) instead. Preloading the data is not neccessary, e.g.:

let url = Bundle.main.url(forResource: "provisiontech", ofType: "htm")

webView.loadFileURL(url, allowingReadAccessTo:
    Bundle.main.resourceURL!.appendingPathComponent("pvtc"))

如果webview仍然无法访问资源,则应考虑是否将页面和所有资源放在同一个文件夹中.

If the webview still cannot access the resources, you should consider whether putting the page and all resources into the same folder.

这篇关于Swift 3 - WKWebView 加载本地 HTML 不加载资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆