cordova-plugin-file: files not accessible after app update (iOS)

Viewed 931

I am experiencing a funny problem: I am developing an ionic app, using cordova-plugin-file to store images. The resulting paths (URIs in form file:///...) are stored in a SQLite DB along with more information. When I install the app and use it, all works perfect. But if I update (or reinstall) the app, the old images are not found anymore, while newly added images work perfect.

I first suspected that the image files were being deleted on update, but I checked the content of the directory and the files are still there. (FYI: I am using file.dataDirectory/scans/ to place my files).

Then I thought that maybe I could go around the problem loading into img src a base64 blob loaded with cordova.file.readAsUrl(), but cordova.file does not find the file as well (I insist, the files are there, I checked with XCode).

So I checked further with cordova.file and it only finds files that are added after last app install, but the older files are still present in the directory.

Here my code:

private getImgSrcFromDocument(doc: Document): any {
        const uri = doc.fileName;
        const src = this.webView.convertFileSrc(uri);
        const sanitized = this.sanitizer.bypassSecurityTrustUrl(src);

        console.log({uri, src, sanitized});
        return sanitized;
    }
<img class="document_thumbnail" [src]="getImgSrcFromDocument(doc)">

I have already checked this, but is not my case.

By the way, the same code works perfect on Android.

Any idea what could be the problem? Thanks in advance!

1 Answers

I found the reason why and the solution (very obvious when you know the problem):

Reason

On every new install, iOS renames the data directory for the app. The directory path has this form:

file:///var/mobile/Containers/Data/Application/ABC0000-1234-99DD-00FA-E835FEA/Library/NoCloud/

The hash in the middle is renewed on every install, so the stored full paths in DB are not valid anymore.

Solution

If you still can do it (no deploy yet, no real users), store only the relative path and complete it every time with this.file.dataDirectory (or wherever you wanted to store your files).

If you already have real users and want your update to 'find the files', just ignore the first part of the stored path and build it like before:

const ValidUri = this.file.dataDirectory + // The injected cordova-plugin-file
                 'relativeSubDirectories/' + // If you store your files in some subdirectory
                 this.document.storedFullPath.substr( // Take from fullPath only the filename
                      this.document.storedFullPath.lastIndexOf('/') + 1
                 );

Where storedFullPath is the string file:///var/mobile/....

After that, you still have to do the webView conversion and the sanitizing, like in the question above.

Hope this helps someone.

Related