@ngenux/react-native-background-downloader
v0.1.4
Published
A React-Native library designed to facilitate file downloads.
Downloads
8
Readme
@ngenux/react-native-background-downloader
A React Native library designed to facilitate the downloading of large files on both iOS and Android, with the ability to perform downloads both in the foreground as well as background.
Why it's useful?
To download large files on iOS, regardless of your app's state (whether it's running in the background or terminated by the OS), you need to utilize the system API known as NSURLSession. This API manages downloads independently from your app and provides updates through delegates (Learn More: Background File Downloads).
On Android, we achieve a similar functionality using the system API known as DownloadManager.
The primary challenge in using this approach is ensuring that your app's user interface remains synchronized with ongoing downloads that may continue even if your app restarts from scratch.
react-native-background-downloader offers a straightforward API for downloading large files and seamlessly reconnecting to those downloads when your app relaunches.
Installation
npm install @ngenux/react-native-background-downloader
Getting started
npm install @ngenux/react-native-background-downloader --save
Mostly automatic installation
$ react-native link @ngenux/react-native-background-downloader
Manual installation
Android
- Open up
android/app/src/main/java/[...]/MainActivity.java
- Add
import com.ngenux.reactnativebackgrounddownloader.ReactNativeBackgroundDownloaderPackage;
to the imports at the top of the file - Add
new ReactNativeBackgroundDownloaderPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-background-downloader' project(':react-native-background-downloader').projectDir = new File(rootProject.projectDir, '../node_modules/@ngenux/react-native-my-native-module/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:compile project(':react-native-background-downloader')
API
startDownload
Function
- Description: Initiates a file download in the background.
- Parameters:
fileUrl
(string): The URL of the file to be downloaded.destinationPath
(string): The local destination path where the downloaded file will be stored.
- Returns: A promise that resolves to download information.
checkDownloadStatus
Function
- Description: Checks the status of a download using its unique
downloadId
. - Parameters:
downloadId
(string): The identifier for the download.
- Returns: A promise that resolves to the download status.
cancelDownload
Function
- Description: Cancels a download in progress using its
downloadId
. - Parameters:
downloadId
(string): The identifier for the download.
- Returns: A promise that resolves when the download is canceled.
stopService
Function
- Description: Stops the background service responsible for handling download progress on Android.
- Returns: A promise that resolves when the service is stopped.
deleteDownloadedFile
Function
- Description: Deletes a previously downloaded file.
- Parameters:
downloadId
(string): The identifier for the download.url
(string): The URL of the downloaded file.
- Returns: A promise that resolves when the file is deleted.
Event Listeners
These functions allow you to add listeners for specific events related to downloads:
addDownloadProgressListener
: Adds a listener for download progress events.addDownloadCompleteListener
: Adds a listener for download completion events. Additionally, it stops the background service on Android after completion.addDownloadFailedListener
: Adds a listener for download failure events.
Usage
import React, { useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import {
addDownloadCompleteListener,
addDownloadFailedListener,
addDownloadProgressListener,
startDownload,
cancelDownload,
checkDownloadStatus,
deleteDownloadedFile,
} from '@ngenux/react-native-background-downloader';
const App = () => {
const [downloadInfo, setDownLoadInfo] = useState(null);
const [progress, setProgress] = useState(0);
useEffect(() => {
// Add a download progress listener
addDownloadProgressListener((event) => {
// @ts-ignore
setProgress(parseInt(event.progress, 10));
});
// Add a download complete listener
addDownloadCompleteListener((event) => {
setProgress(parseInt(event.progress, 10));
setDownLoadInfo((prev) => ({
// @ts-ignore
...prev,
downloadLocation: `file://${event.downloadLocation}`,
}));
});
// Add a download failed listener
addDownloadFailedListener((event) => {
console.log('Download failed:', event);
});
}, []);
const handleStartDownload = async () => {
try {
const info = await startDownload(
'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
'DownloadedVideo.mp4'
);
setDownLoadInfo(info);
} catch (error) {
console.error('Error starting download:', error);
}
};
// @ts-ignore
const handleCheckDownloadStatus = async () => {
try {
// @ts-ignore
const result = await checkDownloadStatus(downloadInfo?.downloadId);
console.log('Download status:', result);
} catch (error) {
console.error('Error pausing download:', error);
}
};
// @ts-ignore
const handleCancelDownload = async () => {
try {
// @ts-ignore
const result = await cancelDownload(downloadInfo?.downloadId);
console.log('Download canceled:', result);
} catch (error) {
console.error('Error canceling download:', error);
}
};
// @ts-ignore
const handleDeleteFile = async () => {
try {
// @ts-ignore
console.log(downloadInfo?.downloadLocation);
const result = await deleteDownloadedFile(
// @ts-ignore
downloadInfo?.downloadId,
// @ts-ignore
downloadInfo?.downloadLocation.replace('file://', '')
);
console.log('File deleted:', result);
} catch (error) {
console.error('Error deleting file:', error);
}
};
return (
<View style={styles.container}>
<Text>Background Download Example </Text>
<Text>Progress : {progress} %</Text>
{/* @ts-ignore */}
<Text>Location : {downloadInfo?.downloadLocation}</Text>
{/* @ts-ignore */}
<Text>Id : {downloadInfo?.downloadId}</Text>
<Button
// @ts-ignore
style={styles.btn}
title="Start Download"
onPress={handleStartDownload}
/>
<Button
// @ts-ignore
style={styles.btn}
title="Check Status"
onPress={handleCheckDownloadStatus}
/>
<Button
// @ts-ignore
style={styles.btn}
title="Cancel Download"
onPress={handleCancelDownload}
/>
<Button
// @ts-ignore
style={styles.btn}
title="Delete File"
onPress={handleDeleteFile}
/>
<Button
// @ts-ignore
style={styles.btn}
title="Empty"
onPress={() => setDownLoadInfo(null)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
},
btn: { width: '90%' },
});
export default App;
License
MIT