ios - 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 中)访问文档文件?
提前致谢,
解决方案
这涵盖了一个文件,但您应该能够使用下面的代码构建一个将相关文件复制到文档目录的函数。
///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 文件。您应该认为捆绑包中的所有内容都是不可变的,并且位置本身只是源源。
推荐阅读
- php - 使用 OAUTH2 登录用户进行 Discord,然后加入 Guild
- python - 如何增强循环中数据框的构建?
- java - 导入Android“包”会导入资源吗?
- opencv - 在 OpenCV 中导入 AutoML 边缘训练模型
- java - 是否可以编写 AOP 注释?
- c# - 删除嵌套集合中的实体
- javascript - 为什么在角度打字稿中使用 onclick 事件必须给它一个 void 类型?
- gradle - Gradle 构建扫描是否安全?
- python - 矩阵内的圆圈
- angular - 我正在尝试从 firestore 获取数据,然后将数据转换为数组。新数组应该是可观察的