如何使用 WKWebview 从 iPad 的文档目录加载 javascript 和 css 资源?

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

我已将所有 .js、.css 和 .html 文件添加到设备文档目录中。在模拟器上,WKWebview 能够成功加载 HTML 所有资源,但在设备上它无法加载 .js 和 .css 文件。

我正在使用此代码 -

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 {
       print(error)
   }

在 HTML 中,我引用 HTML 比如 -

<head>
    <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>
    <style>
        svg {
            -webkit-tap-highlight-color: rgba(0,0,0,0);
        }
    </style>
</head>

所有文件都存储在同一位置。 我陷入了这个问题。需要一些帮助。

WKWebView无法加载本地文件是known issue,可以用loadHTMLString加载简单的内容,但不会设置相关的基本路径即使可能,也会加载文件。

如果您不需要支持 <=ios8 那么您可以为此目的使用新的 API [WKWebView loadFileURL:allowingReadAccessToURL:]

否则,您可能必须在 html 中嵌入所需的 css/js 或使用标准的 UIWebView 或 Safari 视图或其他私有浏览器视图。