16

Hi i'm trying to load an html that is in the main Bundle with WKWebView this worked perfectly with UIWebView but now i have an error, the files in the html does not load send an error in the console : "XMLHttpRequest cannot load"

Consola form simulator

Simulator

this is an example http://proyectoshm.com/esferas/dosaguas/dosaguascitta.html of the content embedded.

My code:

let folder = "maquetas/esferas/\(esfera)"

let resourcePath = Bundle.main.resourcePath
let subdir = URL(fileURLWithPath:resourcePath!).appendingPathComponent(folder, isDirectory: true)

guard let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: folder) else {
    print("no se encontró path")
    return

}
print(subdir.path)


let url = NSURL.fileURL(withPath: path)
 print(url.path)
 vistaweb = WKWebView(frame: self.view.frame)

vistaweb.loadFileURL(url, allowingReadAccessTo: subdir)

self.view.addSubview(vistaweb)
3
  • 5
    Try this vistaweb.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
    – trungduc
    Oct 29, 2017 at 6:46
  • 1
    Like a charm, thanks a lot ! i never found this Oct 29, 2017 at 13:50
  • 1
    You are welcome :)
    – trungduc
    Oct 29, 2017 at 13:51

3 Answers 3

37

To resolve it, you need to turn allowFileAccessFromFileURLs on from WKPreferences

Swift

webView.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")

Objective-C

[webView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
3
  • You may also need to use "allowUniversalAccessFromFileURLs" in addition to the above. See my answer Dec 27, 2019 at 11:16
  • 1
    Add comment to your answer that it is undocumented feature and might stop working unexpectedly. Jul 15, 2020 at 14:48
  • 1
    It seems it does not work anymore (tested on iOS 15.6)
    – gomezo
    Aug 18, 2022 at 9:59
4

File Access and universal File access (In case of reading media from device)

[webView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
[webView.configuration setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
2

For Xamarin.iOS devs:

WKWebViewConfiguration config = webView.Configuration;
config.Preferences.SetValueForKey( FromObject( true ), new NSString( "allowFileAccessFromFileURLs" ) );
config.SetValueForKey( FromObject( true ), new NSString( "allowUniversalAccessFromFileURLs" ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.