Swift 3 - WKWebView Load Local HTML not loading resource files

此生再无相见时 提交于 2021-01-28 07:16:06

问题


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 Project Structure

HTML Page Contents Sample

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)

回答1:


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"))

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



来源:https://stackoverflow.com/questions/45801178/swift-3-wkwebview-load-local-html-not-loading-resource-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!