How can I download the pdf file using apisauce in React Native?

397 Views Asked by At

I am using apisauce for basic http requests like GET and POST, and it works well. Now I need to be able to download pdf files too. Is this possible with apisauce? If so does anyone have some sample code?

1

There are 1 best solutions below

0
On

I am not sure about apisauce, but for pdf download from a url on the internet,

I prefer using this package : rn-fetch-blob as its stable and has good documentation.

Follow these steps:

  1. Run the following command in your Terminal(MAC/Linux) or Command Prompt(Windows)

yarn add rn-fetch-blob

  1. If using CocoaPods, add the pod to your Podfile

pod 'rn-fetch-blob', :path => '../node_modules/rn-fetch-blob'

  1. Import the package in your .js or .tsx file
  2. Add this following code inside the download function and call the function with the download button is pressed

if (Platform.OS === 'android') ==>

        RNFetchBlob.config({
          fileCache: false,
          addAndroidDownloads: {
            useDownloadManager: true,
            notification: true,
            mime: 'application/pdf',
            path:
              `/storage/emulated/0/Download/${file_name}.pdf`,
          },
        })
          .fetch('GET', api, {'Cache-Control': 'no-store'})
          .then((res) => {})
          .catch((errorMessage, statusCode) => {}); 
    

if (Platform.OS === 'ios')

      const {
        dirs: {DownloadDir, DocumentDir},
      } = RNFetchBlob.fs;
      const fPath = `${DocumentDir}/${file_name}.pdf`;
      RNFetchBlob.config({
        fileCache: true,
        path: fPath,
        notification: true,
        appendExt: 'pdf',
      })
        .fetch('GET', api, {
          Authorization: 'Token ' + token,
        })
        .then(async (resp) => {
          RNFetchBlob.fs.writeFile(fPath, resp.data, 'base64');
          RNFetchBlob.ios.previewDocument(fPath);
        });