Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-background-downloader-tavvfiq

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-background-downloader-tavvfiq

patched react-native-background-downloader by ekoLabs.

  • 2.3.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

react-native-background-downloader banner

npm version

react-native-background-downloader

A library for React-Native to help you download large files on iOS and Android both in the foreground and most importantly in the background.

Why?

On iOS, if you want to download big files no matter the state of your app, wether it's in the background or terminated by the OS, you have to use a system API called NSURLSession.

This API handles your downloads separately from your app and only keeps it informed using delegates (Read: Downloading Files in the Background).

On Android we are simulating this process with a wonderful library called Fetch2

The real challenge of using this method is making sure the app's UI is always up-to-date with the downloads that are happening in another process because your app might startup from scratch while the downloads are still running.

react-native-background-downloader gives you an easy API to both downloading large files and re-attaching to those downloads once your app launches again.

Please Note - This library was created to better facilitate background downloading on iOS. If you're not aiming to to use the download-in-background functionality, there are better solutions like RNFS.downloadFile() which will results in a more stable download experience for your app.

ToC

Getting started

$ yarn add react-native-background-downloader

For RN <= 0.57.0 use $ yarn add react-native-background-downloader@1.1.0

Mostly automatic installation

Any React Native version >= 0.60 supports autolinking so nothing should be done.

For anything < 0.60 run the following link command

$ react-native link react-native-background-downloader

Manual installation

iOS
  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modulesreact-native-background-downloader and add RNBackgroundDownloader.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libRNBackgroundDownloader.a to your project's Build PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)
Android
  1. Open up android/app/src/main/java/[...]/MainActivity.java
  • Add import com.eko.RNBackgroundDownloaderPackage; to the imports at the top of the file
  • Add new RNBackgroundDownloaderPackage() to the list returned by the getPackages() method
  1. 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/react-native-background-downloader/android')
    
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
      compile project(':react-native-background-downloader')
    

iOS - Extra Mandatory Step

In your AppDelegate.m add the following code:

...
#import <RNBackgroundDownloader.h>

...

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
{
  [RNBackgroundDownloader setCompletionHandlerWithIdentifier:identifier completionHandler:completionHandler];
}

...

Failing to add this code will result in canceled background downloads.

Usage

Downloading a file

import RNBackgroundDownloader from 'react-native-background-downloader';

let task = RNBackgroundDownloader.download({
	id: 'file123',
	url: 'https://link-to-very.large/file.zip'
	destination: `${RNBackgroundDownloader.directories.documents}/file.zip`
}).begin((expectedBytes) => {
	console.log(`Going to download ${expectedBytes} bytes!`);
}).progress((percent) => {
	console.log(`Downloaded: ${percent * 100}%`);
}).done(() => {
	console.log('Download is done!');
}).error((error) => {
	console.log('Download canceled due to error: ', error);
});

// Pause the task
task.pause();

// Resume after pause
task.resume();

// Cancel the task
task.stop();

Re-Attaching to background downloads

This is the main selling point of this library (but it's free!).

What happens to your downloads after the OS stopped your app? Well, they are still running, we just need to re-attach to them.

Add this code to app's init stage, and you'll never lose a download again!

import RNBackgroundDownloader from 'react-native-background-downloader';

let lostTasks = await RNBackgroundDownloader.checkForExistingDownloads();
for (let task of lostTasks) {
	console.log(`Task ${task.id} was found!`);
	task.progress((percent) => {
		console.log(`Downloaded: ${percent * 100}%`);
	}).done(() => {
		console.log('Downlaod is done!');
	}).error((error) => {
		console.log('Download canceled due to error: ', error);
	});
}

task.id is very important for re-attaching the download task with any UI component representing that task, this is why you need to make sure to give sensible IDs that you know what to do with, try to avoid using random IDs.

Using custom headers

If you need to send custom headers with your download request, you can do in it 2 ways:

  1. Globally using RNBackgroundDownloader.setHeaders():
RNBackgroundDownloader.setHeaders({
    Authorization: 'Bearer 2we$@$@Ddd223'
});

This way, all downloads with have the given headers.

  1. Per download by passing a headers object in the options of RNBackgroundDownloader.download():
let task = RNBackgroundDownloader.download({
	id: 'file123',
	url: 'https://link-to-very.large/file.zip'
	destination: `${RNBackgroundDownloader.directories.documents}/file.zip`,
	headers: {
	    Authorization: 'Bearer 2we$@$@Ddd223'
	}
}).begin((expectedBytes) => {
	console.log(`Going to download ${expectedBytes} bytes!`);
}).progress((percent) => {
	console.log(`Downloaded: ${percent * 100}%`);
}).done(() => {
	console.log('Download is done!');
}).error((error) => {
	console.log('Download canceled due to error: ', error);
});

Headers given in the download function are merged with the ones given in setHeaders.

API

RNBackgroundDownloader

download(options)

Download a file to destination

options

An object containing options properties

PropertyTypeRequiredPlatformsInfo
idStringAllA Unique ID to provide for this download. This ID will help to identify the download task when the app re-launches
urlStringAllURL to file you want to download
destinationStringAllWhere to copy the file to once the download is done
headersObjectAllCostume headers to add to the download request. These are merged with the headers given in the setHeaders function
priorityPriority (enum)AndroidThe priority of the download. On Android, downloading is limited to 4 simultaneous instances where further downloads are queued. Priority helps in deciding which download to pick next from the queue. Default: Priority.MEDIUM
networkNetwork (enum)AndroidGive your the ability to limit the download to WIFI only. Default: Network.ALL

returns

DownloadTask - The download task to control and monitor this download

checkForExistingDownloads()

Checks for downloads that ran in background while you app was terminated. Recommended to run at the init stage of the app.

returns

DownloadTask[] - Array of tasks that were running in the background so you can re-attach callbacks to them

setHeaders(headers)

Sets headers to use in all future downloads.

headers - Object

DownloadTask

A class representing a download task created by RNBackgroundDownloader.download

Members

NameTypeInfo
idStringThe id you gave the task when calling RNBackgroundDownloader.download
percentNumberThe current percent of completion of the task between 0 and 1
bytesWrittenNumberThe number of bytes currently written by the task
totalBytesNumberThe number bytes expected to be written by this task or more plainly, the file size being downloaded

Callback Methods

Use these methods to stay updated on what's happening with the task.

All callback methods return the current instance of the DownloadTask for chaining.

FunctionCallback ArgumentsInfo
beginexpectedBytesCalled when the first byte is received. 💡: this is good place to check if the device has enough storage space for this download
progresspercent, bytesWritten, totalBytesCalled at max every 1.5s so you can update your progress bar accordingly
doneCalled when the download is done, the file is at the destination you've set
errorerrorCalled when the download stops due to an error

pause()

Pauses the download

resume()

Resumes a pause download

stop()

Stops the download for good and removes the file that was written so far

Constants

directories

documents

An absolute path to the app's documents directory. It is recommended that you use this path as the target of downloaded files.

Priority (enum) - Android only

Priority.HIGH

Priority.MEDIUM - Default ✅

Priority.LOW

Network (enum) - Android only

Network.WIFI_ONLY

Network.ALL - Default ✅

Author

Developed by Elad Gil of Eko

License

Apache 2

Keywords

FAQs

Package last updated on 21 Nov 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc