react-nativedownloadreact-native-iosreact-native-fetch-blob

Image is not showing in the iOS device after getting downloaded through rn-fetch-blob ( React native fetch blob)


I am trying to download a small image using this particular code snippet :

Plug in Used : "rn-fetch-blob": "^0.10.14"

 RNFetchBlob.
config({
  fileCache: true,
 
}).
fetch('GET', url, {      //getting image URL from server
  // some headers ..
})
  .then((response) => {
    const base64Str = response.data;
    RNFetchBlob.fs
          .writeFile(imageLocation, base64Str, 'base64')
          .then(() => {
 
              console.log("Download successful");
           
          }).catch((err) => {
            console.log('Failed to save file. ', err);
          });

variable imageLocation points to ${RNFetchBlob.fs.dirs.DocumentDir}/${filename}.

Also tried with ${RNFetchBlob.fs.dirs.CacheDir}/${filename}.

Download is successful but no image is shown in device photos.


Solution

  • On iOS both documents and cache directory are contained within the application's own directory. So you are not storing the image in the device photos.

    To download it to the device photos you need to use CameraRoll from react-native https://facebook.github.io/react-native/docs/cameraroll

    import { CameraRoll } from 'react-native';
    

    This tutorial shows you how to use CameraRoll

    https://medium.com/react-native-training/mastering-the-camera-roll-in-react-native-13b3b1963a2d

    However the crux of it is you can use something like this to download images to the camera roll

    saveToCameraRoll = (image) => {
      if (Platform.OS === 'android') {
        RNFetchBlob
          .config({
            fileCache : true,
            appendExt : 'jpg'
          })
          .fetch('GET', image.urls.small)
          .then((res) => {
            CameraRoll.saveToCameraRoll(res.path())
              .then(Alert.alert('Success', 'Photo added to camera roll!'))
              .catch(err => console.log('err:', err))
          })
      } else {
          CameraRoll.saveToCameraRoll(image.urls.small)
            .then(Alert.alert('Success', 'Photo added to camera roll!'))
      }
    }