Gathering detailed insights and metrics for @kesha-antonov/react-native-background-downloader
Gathering detailed insights and metrics for @kesha-antonov/react-native-background-downloader
Gathering detailed insights and metrics for @kesha-antonov/react-native-background-downloader
Gathering detailed insights and metrics for @kesha-antonov/react-native-background-downloader
@types/kesha-antonov__react-native-background-downloader
TypeScript definitions for @kesha-antonov/react-native-background-downloader
@kesha-antonov/react-native-action-cable
Use Rails 5+ ActionCable channels with React Native for realtime magic.
react-native-zoom-reanimated
Zoom component on react-native + react-native-reanimated + react-native-gesture-handler
node-downloader-helper
A simple http/s file downloader for node.js
About 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.
npm install @kesha-antonov/react-native-background-downloader
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
70 Stars
127 Commits
14 Forks
2 Watching
1 Branches
8 Contributors
Updated on 25 Nov 2024
Java (34.95%)
Objective-C (29.1%)
TypeScript (18.89%)
JavaScript (10.47%)
Ruby (3.41%)
Kotlin (2.42%)
Objective-C++ (0.76%)
Cumulative downloads
Total Downloads
Last day
-26.5%
2,778
Compared to previous day
Last week
-24.8%
13,226
Compared to previous week
Last month
-13.3%
83,966
Compared to previous month
Last year
5,918.8%
698,782
Compared to previous year
1
31
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.
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 using similar process with DownloadManager
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.
@kesha-antonov/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.
1yarn add @kesha-antonov/react-native-background-downloader
or
1npm i @kesha-antonov/react-native-background-downloader
Then:
1cd ios && pod install
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 @kesha-antonov/react-native-background-downloader
Libraries
➜ Add Files to [your project's name]
node_modules
➜ @kesha-antonov/react-native-background-downloader
and add RNBackgroundDownloader.xcodeproj
libRNBackgroundDownloader.a
to your project's Build Phases
➜ Link Binary With Libraries
Cmd+R
)android/app/src/main/java/[...]/MainActivity.java
import com.eko.RNBackgroundDownloaderPackage;
to the imports at the top of the filenew RNBackgroundDownloaderPackage()
to the list returned by the getPackages()
methodandroid/settings.gradle
:
include ':react-native-background-downloader'
project(':react-native-background-downloader').projectDir = new File(rootProject.projectDir, '../node_modules/@kesha-antonov/react-native-background-downloader/android')
android/app/build.gradle
:
compile project(':react-native-background-downloader')
In your AppDelegate.m
add the following code:
1... 2#import <RNBackgroundDownloader.h> 3 4... 5 6- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler 7{ 8 [RNBackgroundDownloader setCompletionHandlerWithIdentifier:identifier completionHandler:completionHandler]; 9} 10 11...
Failing to add this code will result in canceled background downloads. If Xcode complains that RNBackgroundDownloader.h is missing, you might have forgotten to pod install
first.
1import { Platform } from 'react-native' 2import { download, completeHandler, directories } from '@kesha-antonov/react-native-background-downloader' 3 4const jobId = 'file123' 5 6let task = download({ 7 id: jobId, 8 url: 'https://link-to-very.large/file.zip', 9 destination: `${directories.documents}/file.zip`, 10 metadata: {} 11}).begin(({ expectedBytes, headers }) => { 12 console.log(`Going to download ${expectedBytes} bytes!`) 13}).progress(({ bytesDownloaded, bytesTotal }) => { 14 console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`) 15}).done(({ bytesDownloaded, bytesTotal }) => { 16 console.log('Download is done!', { bytesDownloaded, bytesTotal }) 17 18 // PROCESS YOUR STUFF 19 20 // FINISH DOWNLOAD JOB 21 completeHandler(jobId) 22}).error(({ error, errorCode }) => { 23 console.log('Download canceled due to error: ', { error, errorCode }); 24}) 25 26// Pause the task (iOS only) 27task.pause() 28 29// Resume after pause (iOS only) 30task.resume() 31 32// Cancel the task 33task.stop()
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!
1import RNBackgroundDownloader from '@kesha-antonov/react-native-background-downloader' 2 3let lostTasks = await RNBackgroundDownloader.checkForExistingDownloads() 4for (let task of lostTasks) { 5 console.log(`Task ${task.id} was found!`) 6 task.progress(({ bytesDownloaded, bytesTotal }) => { 7 console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`) 8 }).done(({ bytesDownloaded, bytesTotal }) => { 9 console.log('Download is done!', { bytesDownloaded, bytesTotal }) 10 }).error(({ error, errorCode }) => { 11 console.log('Download canceled due to error: ', { error, errorCode }) 12 }) 13}
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.
If you need to send custom headers with your download request, you can do in it 2 ways:
RNBackgroundDownloader.setConfig()
:1RNBackgroundDownloader.setConfig({ 2 headers: { 3 Authorization: 'Bearer 2we$@$@Ddd223', 4 } 5})
This way, all downloads with have the given headers.
RNBackgroundDownloader.download()
:1let task = RNBackgroundDownloader.download({ 2 id: 'file123', 3 url: 'https://link-to-very.large/file.zip' 4 destination: `${RNBackgroundDownloader.directories.documents}/file.zip`, 5 headers: { 6 Authorization: 'Bearer 2we$@$@Ddd223' 7 } 8}).begin(({ expectedBytes, headers }) => { 9 console.log(`Going to download ${expectedBytes} bytes!`) 10}).progress(({ bytesDownloaded, bytesTotal }) => { 11 console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`) 12}).done(({ bytesDownloaded, bytesTotal }) => { 13 console.log('Download is done!', { bytesDownloaded, bytesTotal }) 14}).error(({ error, errorCode }) => { 15 console.log('Download canceled due to error: ', { error, errorCode }) 16})
Headers given in the download
function are merged with the ones given in setConfig({ headers: { ... } })
.
download(options)
Download a file to destination
options
An object containing options properties
Property | Type | Required | Platforms | Info |
---|---|---|---|---|
id | String | ✅ | All | A Unique ID to provide for this download. This ID will help to identify the download task when the app re-launches |
url | String | ✅ | All | URL to file you want to download |
destination | String | ✅ | All | Where to copy the file to once the download is done |
metadata | Object | All | Data to be preserved on reboot. | |
headers | Object | All | Costume headers to add to the download request. These are merged with the headers given in the setConfig({ headers: { ... } }) function | |
isAllowedOverRoaming | Boolean | Android | whether this download may proceed over a roaming connection. By default, roaming is allowed | |
isAllowedOverMetered | Boolean | Android | Whether this download may proceed over a metered network connection. By default, metered networks are allowed | |
isNotificationVisible | Boolean | Android | Whether to show a download notification or not |
returns
DownloadTask
- The download task to control and monitor this download
checkForExistingDownloads()
Checks for downloads that ran in background while you app was terminated. And also forces them to resume downloads.
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
setConfig({})
Name | Type | Info |
---|---|---|
headers | Object | optional headers to use in all future downloads |
progressInterval | Number | Interval in which download progress sent from downloader. Number should be >= 250. It's in ms |
isLogsEnabled | Boolean | Enables/disables logs in library |
A class representing a download task created by RNBackgroundDownloader.download
Members
Name | Type | Info |
---|---|---|
id | String | The id you gave the task when calling RNBackgroundDownloader.download |
metadata | Object | The metadata you gave the task when calling RNBackgroundDownloader.download |
bytesDownloaded | Number | The number of bytes currently written by the task |
bytesTotal | Number | The number bytes expected to be written by this task or more plainly, the file size being downloaded |
completeHandler(jobId)
Finishes download job and informs OS that app can be closed in background if needed. After finishing download in background you have some time to process your JS logic and finish the job.
ensureDownloadsAreRunning
(iOS only)Pauses and resumes all downloads - this is fix for stuck downloads. Use it when your app loaded and is ready for handling downloads (all your logic loaded and ready to handle download callbacks).
Here's example of how you can use it:
Either stop all tasks:
1const tasks = await checkForExistingDownloads() 2for (const task of tasks) 3 task.stop()
Or re-attach them:
1const tasks = await checkForExistingDownloads() 2for (const task of tasks) { 3 task.pause() 4 // 5 // YOUR LOGIC OF RE-ATTACHING DOWLOADS TO YOUR STUFF 6 // ... 7 // 8}
Prepare your app to handle downloads... (load your state etc.)
Add listener to handle when your app goes foreground (be sure to do it only after you stopped all tasks or re-attached them!)
1 2function handleAppStateChange (appState) { 3 if (appState !== 'active') 4 return 5 6 ensureDownloadsAreRunning() 7} 8 9const appStateChangeListener = AppState.addEventListener('change', handleAppStateChange)
ensureDownloadsAreRunning()
after all was setup.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.
Function | Callback Arguments | Info |
---|---|---|
begin | { expectedBytes, headers } | Called when the first byte is received. 💡: this is good place to check if the device has enough storage space for this download |
progress | { bytesDownloaded, bytesTotal } | Called at max every 1.5s so you can update your progress bar accordingly |
done | { bytesDownloaded, bytesTotal } | Called when the download is done, the file is at the destination you've set |
error | { error, errorCode } | Called when the download stops due to an error |
pause()
(iOS only)Pauses the download
resume()
(iOS only)Resumes a paused download
stop()
Stops the download for good and removes the file that was written so far
documents
An absolute path to the app's documents directory. It is recommended that you use this path as the target of downloaded files.
In case of error java.lang.IllegalStateException: TypeToken must be created with a type argument: new TypeToken<...>()
in Android release add this to proguard-rules.pro
:
# Application classes that will be serialized/deserialized over Gson
-keep class com.yourapplicationname.model.api.** { *; }
# Gson uses generic type information stored in a class file when working with
# fields. Proguard removes such information by default, keep it.
-keepattributes Signature
# This is also needed for R8 in compat mode since multiple
# optimizations will remove the generic signature such as class
# merging and argument removal. See:
# https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#troubleshooting-gson-gson
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken
# Optional. For using GSON @Expose annotation
-keepattributes AnnotationDefault,RuntimeVisibleAnnotations
Re-written & maintained by Kesha Antonov
Originally developed by Elad Gil of Eko
Apache 2
No vulnerabilities found.
No security vulnerabilities found.