在与它斗争了几天之后,我找到的解决方案是不使用cdvfile:// 在 iOS 上提供文件。 WkWebView 真的不好用。
但是,WkWebView 可以很好地从本机 file:// 协议加载资产,因此您可以使用以下方法将 cdvfile:// 转换为:
const resolveIosPath = (path) => new Promise((resolve, reject) => {
window.resolveLocalFileSystemURL(path, entry => {
resolve(window.WkWebView.convertFilePath(entry.toURL())
},
reject
)
要使用它,只需通过该方法运行路径并将结果应用于src 属性:
// With async/await
const img = document.createElement("img")
img.src = await resolveIosPath("cdvfile://images/logo.png")
document.body.appendChild(img)
// With Promise chain
resolveIosPath("cdvfile://images/logo.png").then((src) => {
const img = document.createElement("img")
img.src = src
document.body.appendChild(img)
})
// With synchronous img mount, but src added asynchronously
const img = document.createElement("img")
document.body.appendChild(img)
resolveIosPath("cdvfile://images/logo.png").then((src) => {
img.src = src
})
如果您不喜欢异步执行所有这些操作,您可以在应用初始化期间的某个时间保存根目录:
// Storing on `window` just as an example, the point is to make it globally available
window.cacheRoot = await resolveIosPath("cdvfile://")
...然后你可以像这样同步使用它:
const img = document.createElement("img")
img.src = window.cacheRoot + "logo.png"
document.body.appendChild(img)