npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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

  1. 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 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/@ngenux/react-native-my-native-module/android')
  2. 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

Author

Developed by ng-sushil of @ngenux