首页 > 解决方案 > iOS:WKWebview 如何允许位于 bundle 中的 html 文件读取文档目录

问题描述

我有一个位于捆绑包中的 html 文件,并且我正在使用 WKWebView 从该 html 加载内容:

let fileURL = URL(fileURLWithPath: Bundle.main.path(forResource:"demo", ofType: "html")!)
    webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)

然而,这个 html 文件有一些脚本试图访问位于 Documents 目录中的文件(一些视频保存在那里),但得到“无法加载本地资源”。错误。我在 AVPlayerViewController 的其他地方使用这些文件,所以我知道这些文件存在并且我使用的 url 是正确的。

我试过了:

1.将文档目录 url 传递给 allowedReadAccessTo 参数 - webview 甚至不加载

2.将文件目录中的项目复制到 tmp 目录并在脚本中传递这个 (tmp dir) url -它可以工作,但是这个过程发生的太多了,由于内存问题和时间,我不想复制这么多文件它需要大文件。

3.将 html 文件及其脚本从捆绑包复制到文档目录 -不相关,因为我使用的脚本不时更改,因此为了确保用户始终拥有(脚本的)最新版本,我将不得不复制每次应用程序启动时。

那么,有没有其他方法可以让 html 文件(位于 bundle 中)访问文档文件?

提前致谢,

标签: iosswiftwebviewwkwebview

解决方案


这涵盖了一个文件,但您应该能够使用下面的代码构建一个将相关文件复制到文档目录的函数。

///Copy the file from the bundle to the Documents Directory
guard let bundleURL = Bundle.main.url(forResource:"demo", ofType: "html") else {
     preconditionFailure("Unable to get bundle URL") 
}

guard let documentsDirectory = let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
     preconditionFailure("Unable to get Documents URL") 
}

let newURL = documentsDirectory.appendingPathComponent("demo.html")

do {
   try FileManager.default.copyItem(at: bundleURL, to: newUrl)
} catch {
   print("Error copying bundle: \(error)")
}


///Setup the WKWebView
let prefs = WKPreferences()
prefs.javaScriptEnabled = true

let webConfig = WKWebViewConfiguration()
webConfig.preferences = prefs

var webViewer = WKWebView(frame: view.frame, configuration: webConfig)
webViewer.loadFileURL(newURL, allowingReadAccessTo: documentsDirectory)

请记住,Bundle 在您的应用程序中完全位于不同的目录中。仅仅因为文件可以访问文档目录并不意味着文件中的 HTML 将能够找到您正在引用的引用脚本或其他 HTML 文件。您应该认为捆绑包中的所有内容都是不可变的,并且位置本身只是源源。


推荐阅读