Search code examples
iosionic-frameworkcapacitorionic5

How to save file with Capacitor on iOS?


I have the following code (adapted from this tutorial) that I use for saving files from backend:

import { FilesystemDirectory, Plugins } from '@capacitor/core';
const { Filesystem } = Plugins;

await Filesystem.writeFile({
    path: "filename.txt",
    data: "base64 data",
    directory: FilesystemDirectory.Documents,
  });

This codes works fine on Android, even creates the Documents directory in the root of internal storage. Unfortunately, on iOS no file is created, no mater what directory I use (I've tested it with Documents, Data and ExternalStorage). When I put this code block inside try..catch, nothing is thrown, so the operation is supposedly completed successfully, just no file is saved. Tested on one Android device and two iOS.


Solution

  • iOS doesn't allow accessing file storage directly. I made it work with Ionic-native's FileOpener like this:

    import { FileOpener } from '@ionic-native/file-opener/ngx';
    import { FilesystemDirectory, Plugins } from '@capacitor/core';
    const { Filesystem } = Plugins;
    
    const result = await Filesystem.writeFile({
        path: "filename.txt",
        data: "base64 data",
        directory: FilesystemDirectory.Documents,
      });
    this.fileOpener.showOpenWithDialog(result.uri, 'application/json')
    

    It opens a dialog where you can select where to save your file. It's a bit confusing as the function's description is "Opens with system modal to open file with an already installed app" but saving works with it as well.

    You need to also install cordova-plugin-file-opener2 and put ionic FileOpener to providers in app.module.ts. If you are not using Cordova otherwise, you don't need to do Cordova setups, it works alongside Capacitor as a separate plugin. As far as I'm aware, Capacitor doesn't provide a solution for downloading in iOS.