I am struggling to figure out the best approach for handling large, long-running uploads in my Ionic + Capacitor mobile app.
Specifically, I am uploading a few dozen photos (~30+) to Firebase storage and one or more videos (1-2 minutes) to Vimeo all at roughly the same time. Users may even have several batches of these uploads running simultaneously (the user can choose when to do their uploads). On a good connection the entire upload process takes < 1 minute, but I have to account for slow/spotty connections, as well as users going online and offline.
The uploads work pretty much perfectly when the app is in the foreground, but the issues begin when the user exits or completely closes the app during the upload. I don't have a reliable mechanism to ensure my uploads continue running.
I am using Capacitor v2 at the moment, so I am trying to use the BackgroundTask
plugin to attempt to keep uploads alive as long as possible, but this has proven to be unreliable.
https://capacitorjs.com/docs/v2/apis/background-task
const uploadPromises = []; // Array of promises used to track each individual upload
// Start uploading things, adding each unresolved upload to 'uploadPromises'
const { isActive } = listenForCapacitorAppStateChange(); // This is a redux-saga emitter
if (!isActive) {
const taskId = BackgroundTask.beforeExit(async () => {
// Use the background task to wait for all upload promises to resolve
await Promise.allSettled(uploadPromises);
// Alert OS that background task is finished
BackgroundTask.finish({ taskId });
});
}
I am also checking when the app is restored to resume any uploads that didn't finish for some reason, but this is frustrating because users may start uploading, exit the app, and then come back some time later to find their upload is still incomplete and sitting idle that whole time!
Now I am reading about Capacitor v3 and see that they've completely removed the BackgroundTask
plugin, but the v2 docs make that plugin seem very important:
This is especially important on iOS as any operations would normally be suspended without initiating a background task.
Since my solution seems hacky at best, and is not very reliable, and now the Capacitor team is removing the plugin entirely, that leads me to believe I am missing a completely different (ie. better) solution to this problem.
Does anyone know of an existing solution? Do I need to write my own plugin to kick off a proper background service for Android and iOS just to keep my uploads alive? I haven't come across a community plugin yet that seems to cover this.