I am trying to use cordova-plugin-file
to save a file generated in the app, into the phone storage, and inside the Documents or Files folder if possible.
The file is getting saved, I can see its path, but I cannot access its location when I am on iOs, because it's outside the Files
directory. This is my code, and it's working for Android.
I also added inside the config.xml the following:
<preference name="iosPersistentFileLocation" value="Compatibility" />
.........
const mimeType = 'application/json';
const filename = 'test.json';
const data = await this.http.get(`${environment.backUrl}/get-data`).toPromise();
const jsonString = JSON.stringify(data, null, '\t');
const blob = new Blob([jsonString], { type: mimeType });
if (window.cordova && window.cordova?.platformId !== 'browser') {
document.addEventListener('deviceready', () => {
let storageLocation = '';
if (window.cordova?.platformId === 'android') {
storageLocation = window.cordova.file.externalRootDirectory + 'Documents/';
}
if (window.cordova?.platformId === 'ios') {
storageLocation = window.cordova.file.documentsDirectory;
}
(window as any).resolveLocalFileSystemURL(
storageLocation, (dir) => {
dir.getFile(
filename, {create: true},
(file) => {
file.createWriter(
(fileWriter) => {
fileWriter.write(blob);
fileWriter.onwriteend = () => {
let url = file.toURL();
alert('File Saved inside: ' + url);
};
fileWriter.onerror = (err) => {
alert('File not saved');
console.error(err);
};
}
);
}
);
}
);
});
}