I'm trying to have a share button, that would take a screenshot of the current place in the app, and share it to social platforms along with some text or a link.
I've tried using expo-sharing, react-native-view-shot, and expo-file-system, and another try using the core react-native share and react-native-view-shot, and I either succeed on sharing a screenshot, or sharing a text, but not both. I've looked around a lot and still didn't have success with it.
Here are the most successful 2 tries:
First code with expo-sharing, expo-file-system, and react-native-view-shot, shares the screenshot but not the text message:
const viewShot = React.useRef();
const onShare = async () => {
try {
const uri = await viewShot.current.capture();
const message = 'Your message here';
// create a temporary file that contains the image and the message
const tempFilePath = `${FileSystem.cacheDirectory}TempImage.jpg`;
await FileSystem.writeAsStringAsync(tempFilePath, message, {
encoding: FileSystem.EncodingType.UTF8,
});
await FileSystem.copyAsync({
from: uri,
to: tempFilePath,
});
// share the temporary file using the `Sharing.shareAsync` method
//await Sharing.shareAsync(`file://${tempFilePath}`, { message });
await Sharing.shareAsync(uri, { message });
} catch (error) {
console.error('Oops, snapshot failed', error);
}
};
or
const viewShot = React.useRef();
const onShare = async () => {
try {
const uri = await viewShot.current.capture();
const message = 'Your message here';
//await Sharing.shareAsync(`file://${tempFilePath}`, { message });
await Sharing.shareAsync(uri, { message });
} catch (error) {
console.error('Oops, snapshot failed', error);
}
};
return (
<ViewShot
style={{flex:1}}
ref = {viewShot}
options={{ format: "png", quality: 0.9 }}
>
<NavigationContainer>
<Tab.Navigator
......
Second code with core share module from react-native, expo-file-system, and react-native-view-shot, shares the message but not the screenshot:
const viewShot = useRef(null);
const onShare = async () => {
try {
console.log('Sharing...');
const uri = await takeScreenshot();
console.log('URI:', uri);
await Share.share({
title: 'Share Screenshot',
message: 'Check out this screenshot!',
url: `file://${uri}`,
});
console.log('Shared successfully');
} catch (error) {
console.log(error.message);
}
};
const takeScreenshot = async () => {
try {
console.log('Taking screenshot...');
const uri = await viewShot.current.capture();
console.log('Screenshot taken:', uri);
const temporaryDirectory = FileSystem.documentDirectory + 'screenshot.png';
await FileSystem.copyAsync({ from: uri, to: temporaryDirectory });
console.log('Screenshot saved to:', temporaryDirectory);
return temporaryDirectory;
} catch (error) {
console.log(error.message);
throw error;
}
};
This functionality seems trivial but I still haven't managed to make it work. Thanks.