Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift WKWebView Loading local file not working on a device

I am having some issues when trying to run my app on an iPad (or any device) it runs as expected on the emulator so it is weird that it doesn't work on a device. I was wondering if some one could point me in the correct direction. I spend many hours reading all the other posts on here about the same issues, however none of the suggested solutions worked.

I have a WKWebView into which I am loading a local html file. On the emulator the file loads and everything works fine but on a device I am getting a message in the log:

Could not create a sandbox extension for '/'

Here is the code I have that loads the file into the

override func viewDidLoad() {
    super.viewDidLoad()
    var path = NSBundle.mainBundle().pathForResource("Login_UK",
        ofType: "html")
    var url = NSURL(fileURLWithPath: path!)
    var request = NSURLRequest(URL: url!)

    var theConfiguration = WKWebViewConfiguration()
    theConfiguration.userContentController.addScriptMessageHandler(self,
        name: "callbackHandler")

    webView = WKWebView(frame: self.view.frame,
        configuration: theConfiguration)
    webView!.loadRequest(request)
    self.view.addSubview(webView!)
}

Any help will be greatly appreciated

Kind Regards, Dimitar

like image 616
Dimitar Dyankov Avatar asked Jan 06 '15 16:01

Dimitar Dyankov


2 Answers

Thank you for any one who tried to answer my question. I have released that this is an error with the WebKit lib that Apple are trying to fix. However I have found a good workaround that required little work.

I open the local file and read its content and then send that string into a webView.loadHTMLString method that compiles the hmtl that was in the file. That way you avoid the issues with iOS not being able to find the path to the local file.

Here is an example of reading a file and then opening it for any one who has the same issues:

    let path2 = NSBundle.mainBundle().pathForResource("index", ofType: "html")
    var text = String(contentsOfFile: path2!, encoding: NSUTF8StringEncoding, error: nil)!

    webView!.loadHTMLString(text, baseURL: url)

Kind regards, Dimitar

like image 92
Dimitar Dyankov Avatar answered Oct 19 '22 23:10

Dimitar Dyankov


Just do this:

if url.isFileURL {
    webView.loadFileURL(url, allowingReadAccessTo: url)
} else {
    let request = URLRequest(url: url)
    webView.load(request)
}
like image 23
drewster Avatar answered Oct 20 '22 01:10

drewster