【问题标题】:WKWebView cannot load local resource in HTMLWKWebView 无法在 HTML 中加载本地资源
【发布时间】:2017-09-12 10:53:15
【问题描述】:

我从本地应用程序“文档”文件夹加载了 HTML 页面,其中包含结构化目录。 “main”文件夹存放首页和资源,“interactive”文件夹存放另一个模块,通过首页重定向。

我在“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不支持“文档”文件夹下的复杂文件夹结构,我应该如何纠正它?谢谢。

这个简单的在 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.")
  }
}

【问题讨论】:

    标签: ios swift3 wkwebview


    【解决方案1】:

    在您的项目中添加所有 HTML 目录和文件。

    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
    }
    

    【讨论】:

    • 在“Documents”目录下工作怎么样,为什么会失败?我的目标是存储在“文档”目录中并允许互联网更新文件。
    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2017-03-22
    • 1970-01-01
    相关资源
    最近更新 更多