Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load local html files from applications's document directory swift wkwebview

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

like image 206
milsha Avatar asked Sep 17 '25 04:09

milsha


1 Answers

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)!)
like image 61
AleyRobotics Avatar answered Sep 19 '25 20:09

AleyRobotics