Loading local css & js files into WKWebView

Fred J. picture Fred J. · Jan 4, 2016 · Viewed 13.6k times · Source

in Swift 2.1.1 & Xcode 7.1
My code uses WKWebView and loads index.html form a local file but fails to load index.css and other javascript files as shown in the head tag.

My best guess is that the baseURL is not correct, if so, How can I set the baseURL correctly? Thanks

import UIKit
import WebKit

class ViewController: UIViewController {
@IBOutlet var containerView: UIView! = nil  //allows the class to refrence WKWebView
var webView: WKWebView?

override func loadView() {
    super.loadView()

    self.webView = WKWebView()
    self.view = self.webView!
}

override func viewDidLoad() {
    super.viewDidLoad()

    let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
    let HTMLString: NSString?

    do {
        HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
        let baseUrl  = NSURL.fileURLWithPath("")
        webView!.loadHTMLString(HTMLString as! String, baseURL: baseUrl)

    } catch {
        HTMLString = nil
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

enter image description here

Answer

Fred J. picture Fred J. · Jan 5, 2016

After a bit of reading here about the file url I was able to solve the problem.

Here is the code

import UIKit
import WebKit

class ViewController: UIViewController {
    @IBOutlet var containerView: UIView! = nil  //allows the class to reference WKWebView
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let baseUrl = NSURL(string: "file:///<yourFilePath>/abc/")
        let path = NSBundle.mainBundle().pathForResource("abc/index", ofType: "html")
        let HTMLString: NSString?

        do {
            HTMLString = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
            webView!.loadHTMLString(HTMLString as! String, baseURL: baseUrl )

        } catch {
            HTMLString = nil
        }
    }
}