WKWebView无法在HTML

时间:2017-09-12 10:53:15

标签: ios swift3 wkwebview

我从本地应用“Documents”文件夹加载HTML页面,带有结构化目录。 “主”文件夹存储主页和资源,“交互”文件夹存储另一个模块,通过主页重定向。

enter image description here

我在“main”文件夹中加载“ipad.html”,页面无法加载资源(即css / js文件)来显示正确的样式。像这样的代码。

let indexHTML = "ipad.html"
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath: String = path[0]
let folderPath = documentDirectoryPath.appending("/main")
let destinationURLForFile = URL(fileURLWithPath: folderPath + "/\(indexHTML)")
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)

do{
    let fileName =  try String(contentsOf: destinationURLForFile, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    webView.loadHTMLString(fileName, baseURL: baseUrl)

}catch{
    print("Loading HTML failed.")
}

在“ipad.html”里面这样。

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>demo</title>
    <meta name="description" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <link rel="stylesheet" href="./css/animate.min.css">
    <link rel="stylesheet" href="./css/style.css">

    <script src="./bower_components/modernizr/modernizr-2.5.3.min.js"></script>
</head>
<body class="page-ipad-landing animated" lang="">
......
......
</body>
</html>

但我将其移至Bundle.main,并删除“main”文件夹以加载“ipad.html”正确显示。为什么不同的行为或iOS不支持“Documents”文件夹下的复杂文件夹结构,我该如何纠正?感谢。

这个简单的在Bundle.main文件夹中正常工作。

if let url = Bundle.main.url(forResource: "ipad", withExtension: "html") {
  do {
       let contents = try String(contentsOfFile: url.path)
       webView.loadHTMLString(contents, baseURL: url.deletingLastPathComponent())
  } catch {
     print("Could not load the HTML string.")
  }
}

1 个答案:

答案 0 :(得分:0)

添加所有HTML目录&amp;项目中的文件。

let webView = WKWebView()
if let htmlPath = Bundle.main.path(forResource: "directory/index", ofType: "html") {
  let htmlUrl = URL(fileURLWithPath: htmlPath, isDirectory: false)
  webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
  view = webView
}

enter image description here