'Cordova + cordova-ios 6.1.0 - load local image

I have a cordova app that worked great prior to using cordova-ios 6.x.

This app downloads couple of images into cordova.file.dataDirectory for offline access.... so far I haven't been able to find a way to display this image other than using local webserver plugin.

Isn't there any other built-in way how to allow serve content from the cdvfile scheme ? [i need to set an img src] as there may be many images, converting to base64 is not an option for me.

Any help appreciated



Solution 1:[1]

After spending several days battling with it, the solution I found was to not use cdvfile:// to serve the files on iOS. WkWebView really doesn't play nice with it.

However, WkWebView is perfectly fine loading assets from the native file:// protocol, so you can convert the from cdvfile:// to that using this:

const resolveIosPath = (path) => new Promise((resolve, reject) => {
  window.resolveLocalFileSystemURL(path, entry => {
    resolve(window.WkWebView.convertFilePath(entry.toURL())
  },
  reject
)

To use it, simply run your path through that method and apply the result to the src attribute:

// 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
})

If you don't like having to do all of that asynchronously, you can save the root sometime during your app's initialization:

// Storing on `window` just as an example, the point is to make it globally available
window.cacheRoot = await resolveIosPath("cdvfile://")

...and then you can use it synchronously like this:

const img = document.createElement("img")
img.src = window.cacheRoot + "logo.png"
document.body.appendChild(img)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AegisToast