从应用程序的文档目录中加载本地html文件swift wkwebview

时间:2019-01-29 08:02:50

标签: ios swift wkwebview

我正在尝试加载本地html文件,该文件通过wkwebview下载到我的应用程序中。与此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 occured trying to load the resource,页面即将出现:空白

2 个答案:

答案 0 :(得分:0)

迅速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)!)

答案 1 :(得分:0)

URLRequest主要用于实时网址。对于系统文件,只需加载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?

因此:

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