首页 文章

Swift 3 - WKWebView加载本地HTML不加载资源文件

提问于
浏览
1

我从网上下载我的网站到存储在xcode项目中的子文件夹,并希望在本地运行WKWebView . 我发现webview加载的网页错过了所有CSS / JS / Images资源 . 我在互联网上搜索仍然没有工作 . 相对网址内的网页是否不正确或我的代码是否导致主捆绑位置问题?有人可以帮忙 . 谢谢 .

Xcode Project Structure

HTML Page Contents Sample

我写了这段代码来加载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 回答

  • 1

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

    let url = Bundle.main.url(forResource: "provisiontech", ofType: "htm")
    
    webView.loadFileURL(url, allowingReadAccessTo:
        Bundle.main.resourceURL!.appendingPathComponent("pvtc"))
    

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

相关问题