Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cancel Download function not working #370

Open
TirumalReddy opened this issue Jun 14, 2024 · 5 comments
Open

Cancel Download function not working #370

TirumalReddy opened this issue Jun 14, 2024 · 5 comments

Comments

@TirumalReddy
Copy link

Description:
The cancel() method in react-native-blob-util is not functioning as expected. When attempting to cancel an ongoing download, the download continues instead of being halted.

Steps to Reproduce:

Start a download using react-native-blob-util.
Attempt to cancel the download using the cancel() method.
Observe that the download continues despite the cancellation attempt.

Expected Behavior:
The download should be halted immediately upon calling the cancel() method.

Actual Behavior:
The download continues even after calling the cancel() method.

Environment:

Library Version: 0.18.6
React Native Version: 0.71.7
Platform: Android & IOS

Code Example:

       let DownloadDir = "Storage/to/Path"
        let fileName = Name + extension;
        let filePath = DownloadDir + fileName;
        let folderName = DownloadDir + Name;
        
        let options = {
            fileCache: true,
            addAndroidDownloads: {
                useDownloadManager: true,
                notification: false,
                path: filePath,
                description: "downloading...",
            },
            path: filePath,
        };


       const task = config(options)
            .fetch("GET", FILE_URL)
            .progress((received, total) => {
                const progress = Math.floor((received / total) * 100);
            })
            .then((res) => {
                console.log("res)
            })
            .catch((error) => {
                if (fs.exists(folderName)) {
                    fs.unlink(folderName);
                }
            });


        task.cancel((err) => {
          if (err) {
            console.error('Failed to cancel download:', err);
          } else {
            console.log('Download cancelled successfully');
          }
      });
@TirumalReddy
Copy link
Author

@RonRadtke @pcardon Can you please check it once

@anilunni
Copy link

Even I also facing the same issue. Kindly give the solutions for the same @pcardon / @RonRadtke

@KSNMURTHY08
Copy link

Hi,

I am also wanted to cancel the ongoing download. I have tried abortController and tried to abort/cancel the download but is also not working. I am also using react-native-blob-util. Please find the below code snippet I have tried.

import React, { useState } from 'react';
import { View, Button, Text, StyleSheet, PermissionsAndroid, Platform } from 'react-native';
import RNFetchBlob from 'react-native-blob-util';

const DownloadComponent = () => {
const [isDownloading, setIsDownloading] = useState(false);
const [downloaded, setDownloaded] = useState(false);
const [error, setError] = useState(null);
const [controller, setController] = useState(null);

const requestStoragePermission = async () => {
try {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Storage Permission Required',
message: 'App needs access to your storage to download files',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
}
return true;
} catch (err) {
console.warn(err);
return false;
}
};

const startDownload = async () => {
const hasPermission = await requestStoragePermission();
if (!hasPermission) {
setError('Permission denied');
return;
}
const abortController = new AbortController();
setController(abortController);
setIsDownloading(true);
setDownloaded(false);
setError(null);
RNFetchBlob.config({
fileCache: true,
path: RNFetchBlob.fs.dirs.DownloadDir + '/test-download.pdf',
})
.fetch('GET', 'https://example.com/test-download.pdf', null, abortController.signal)
.progress((received, total) => {
console.log('progress', received / total);
})
.then((res) => {
console.log('The file saved to ', res.path());
setDownloaded(true);
setIsDownloading(false);
setController(null);
})
.catch((err) => {
if (err.name === 'AbortError') {
console.log('Download cancelled');
} else {
console.error(err);
setError(err.message);
}
setIsDownloading(false);
setController(null);
});
};

const cancelDownload = () => {
if (controller) {
controller.abort();
}
};

return (



{isDownloading && Downloading...}
{downloaded && Download Complete!}
{error && Error: {error}}

);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});

export default DownloadComponent;

@Shivakumaramm
Copy link

Shivakumaramm commented Jun 19, 2024

Facing the same . Please provide the solution for the same

@shubhamjadon
Copy link

@TirumalReddy The confusion seems to stem from the fact that the cancel method exists on the fetch function in the react-native-blob-utils library, but you're trying to chain it to a promise result, which won't work.

Here is code snippet from docs:

let task = ReactNativeBlobUtil.fetch('GET', 'http://example.com/file/1')

task.then(() => { ...
})
        // handle request cancelled rejection
        .catch((err) => {
            console.log(err)
        })
// cancel the request, the callback function is optional
task.cancel((err) => { ...
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants