zedArt
zedArt

Reputation: 485

rn-fetch-blob ask for storage automatically

I tried to download pdf file with rn-fetch-blob, first thing I add permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

then I use this code:

_downloadFile2 = () => {
  let DownloadDir = RNFetchBlob.fs.dirs.DownloadDir
  let options = {
    fileCache: true,
    addAndroidDownloads : {
      useDownloadManager : true,
      notification : true,
      title : "file name",
      path: DownloadDir + '/' + "fileName"+ '.' + 'pdf',
      description : 'download fileName'
    }
  }
  RNFetchBlob.config(options)
  .fetch('GET', 'link....')
  .catch((err) => {console.warn('error' + err)})
};

my code works fine but I have to set STORAGE PERMISSION manually, what I want is to ask for storage automatically like when I want to use camera I had put this permission and it show me alert with an allow button, I don't know why it doesn't work with storage !

Second think is that I can't download my file 2 times. firt time (after allowed storage permission manually) it works fine but whene I click on button to redownload it I have an error or it deosn't anything it depends on the emulator error what I have is: 1. message alert with 'download unsuccessful' 2. I console.wanr error and I have this: Error: Download manager failed to download from 'link...' Status Code = 16

I think there is something with cach, but I don't know what to do

Upvotes: 0

Views: 3441

Answers (1)

vitosorriso
vitosorriso

Reputation: 775

To manually ask for permission:

import { PermissionsAndroid, Platform } from 'react-native'

_downloadFile2 = async () => {
  if (Platform.OS === 'android') {
    await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE)
    await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE)
  }
}
// rest of the code

Also, remember, on iOS you don't have fs.dirs.DownloadDir, you should use fs.dirs.DocumentDir for iOS only.

Upvotes: 3

Related Questions