0

I'm trying to save a base64 encoded image in iOS using react-native-share and also Share module from React Native. But both fail when trying the Save Image option.

React Native Share

try {
  const sharedResponse = await Share.open({ url: dataUri });
  console.log(sharedRes);
} catch (error) {
  console.log(error);
}

Share Module

try {
  const sharedResponse = await Share.share({ url: dataUri });
  console.log(sharedRes);
} catch (error) {
  console.log(error);
}

Options other than Save image such as copy, and save to files are working fine.

I have added the following in Info.plist as well

<key>NSPhotoLibraryAddUsageDescription</key>
<string>APP wants to save to photos</string>

This is working fine on the first try in the app's lifetime (When it's asking the permissions from the user). After that this functionality doesn't work.

Iva
  • 2,447
  • 1
  • 18
  • 28
tharwi
  • 67
  • 11

3 Answers3

0

For some reason you need to write the file to the temp directory first before sharing. I'm not sure the reasoning behind this... but it did fix the issue for me.

const filename = `snapshot.jpeg`; // or some other way to generate filename
const filepath = `${FileSystem.cacheDirectory}/${filename}`;
await FileSystem.writeAsStringAsync(filepath, res.data, { encoding: 'base64' });

const isSharingAvailable = await isAvailableAsync();

if (!isSharingAvailable) {
    showAlert('Error', 'Sharing is not available.')
    return;
}

if (Platform.OS === 'ios') {
    //sharing just the file allows for more applications to be shared too.  Adding a message seems to remove many apps from the sharing list
    await Share.share({ url: filepath });
}
Ben Walton
  • 399
  • 3
  • 11
0

This strange behaviour had happened because I'm trying to open the Share pop-up above a React Native Modal. The issue didn't occur if I try to hide the Modal before the Share pop-up comes up.

tharwi
  • 67
  • 11
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 21 '22 at 01:25
0

I resolved the issue when storing the image locally before opening the Share Modal. To store the image i used the npm package 'react-native-fs' and then use it just like this:

import RNFS from "react-native-fs";

function storeFileLocally(url: string): Promise<string> {

     const localFile = `${RNFS.DocumentDirectoryPath}/tempFile.jpeg`;

     const options: RNFS.DownloadFileOptions = {
           fromUrl: url,
           toFile: localFile
     };

     return RNFS.copyFile(url, localFile)
                .then(() => 'file://'+localFile)
                .catch((error) => {
                    console.error(error);
                    return null;
            });
}