Jagveer Singh Rajput Jagveer Singh Rajput - 1 year ago 299
iOS Question

How to load javascript and css resources from Document directory of iPad using WKWebview?

I have added all .js, .css and .html files in Device document directory. On simulator , WKWebview is able to load HTML with all resources successfully but on device it is not able to load .js and .css files.

I am using this code -

let baseURL = "file:///var/mobile/Containers/Data/Application/61AAA238-BE0C-4CD1-8401-58D0A40BBDF0/Documents/SitePlanResources/"
do {
let fullPath = "/var/mobile/Containers/Data/Application/61AAA238-BE0C-4CD1-8401-58D0A40BBDF0/Documents/SitePlanResources/sitemap_708_193.html"
let htmlString = try NSString(contentsOfFile: fullPath!, encoding: String.Encoding.utf8.rawValue)
_ = self.masterWebView?.loadHTMLString(htmlString as String, baseURL: baseURL)
} catch {

In HTML, I am referencing HTML like -

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=6.0" />
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<link href="preview.css" rel="Stylesheet" type="text/css" />
<link href="simple-slider.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-migrate-1.2.1.js"></script>
<script type="text/javascript" src="jquery.svg.min.js"></script>
<script type="text/javascript" src="MasterSitePlan.js"></script>
<script type="text/javascript" src="Tap.js"></script>
<script src="fastclick.js" type="text/javascript"></script>
<script type="text/javascript" src="simple-slider.js"></script>
svg {
-webkit-tap-highlight-color: rgba(0,0,0,0);

All files are stored in same location.
I got stuck in this problem. Need some help.

Answer Source

It is a known issue of WKWebView to not be able to load a local file, you can load a simple content with loadHTMLString, but this will not set a base path from which the related files will be loaded even if possible.

If you don't need to support <=ios8 then you can use a new API for such purpose [WKWebView loadFileURL:allowingReadAccessToURL:]

Otherwise you will probably have to either embed the needed css/js in the html or use the standard UIWebView or Safari view or another private browser view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download