Ionic-Native File read and write only works in live reload mode


#1

Hey Everyone,

I have a strange error that I hope someone can help me with.

I have developed some functionality using the Native File plugin that is used to read and write files to the device storage. This has been working fine during development when running my app with the command:

ionic cordova run android -l

But when I choose to use:

ionic cordova run android

The file read and write functionality doesn’t work?!?

Here is an example of the code that is no longer working:

saveImageToDevice(projectKey: string, imageData: Blob | string, imageName: string): Promise<any> {
        return new Promise((resolve, reject) => {            
                let options: IWriteOptions = {
                    replace: true
                }
                this.file.writeFile(this.file.externalDataDirectory + projectKey, imageName, imageData, options).then(fileWriteRes => {
                    resolve(fileWriteRes)
                }).catch(err => {
                    console.log("There was an error writing the file")
                    console.error(err)
                })
            })
        })
    }

Everything works as expected when I run the app with the live reload option, but when I without the live reload option… the promise just hangs and never resolves or rejects.

What could be causing this??


#2

To eliminate one source of potential problems (and to improve the code quality), get rid of the explicitly instantiated Promise entirely, and simply return the one that writeFile() gives you.


#3

Thanks for the suggestion. I’m returning a promise like that because in my actual code I’m chaining several promises together - I removed the other promise functions in my post for simplicity.

I have half solved my problem…
Writing files by passing in a Blob would hang and never cause the promise to resolve or reject.
Changing this to write files by passing in an ArrayBuffer works - any idea why this might be?

Also…

Reading files by using either File.ReadAsArrayBuffer(…) or File.ReadAsDataURL(…) both result in the same promise that just hangs and never resolves…

Any other ideas? I’m stumped


#4

Ok I figured it all out… It turns out the way that I was downloading and saving the files was somehow wrong.

I have fixed the issue by using the FileTransfer plugin from ionic-native. In my case I’m using Firebase Storage to store the files… downloading and saving them was trivial. Then I just load them in the application using their native file URI


#5

Hey.
we see the exact same behavior with file.readAsDataURL.
how did you resolved? i am using file transfer to write the file (which works great) but when trying to read the file (without live reload flag enabled) the promise never returns.

appreciate some help.

Thanks Yosi


#6

load cordova.js after polyfill.js in index.html made it for me so far.