Reputation: 99
I am trying to load a local html file which is downloaded to my application with wkwebview. Along with this html file i am downloading two js files, they are referenced inside the html file.
But what ever i do, they are not loading in 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)
}
My html file
<!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>
But it is not loading on the screen from safari(Develop/) i can see that An error occured trying to load the resource
, page is coming as about:blank
Upvotes: 4
Views: 4969
Reputation: 13364
URLRequest
is basically made for live url. For system file just load the URL
. You need to use below method and it will work:
/*! @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)
Upvotes: 2
Reputation: 970
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)!)
Upvotes: 2