Skip to content

Instantly share code, notes, and snippets.

@faberyx
Last active March 6, 2023 14:48
Show Gist options
  • Save faberyx/30bed36ed1806f252396908a9ad3c932 to your computer and use it in GitHub Desktop.
Save faberyx/30bed36ed1806f252396908a9ad3c932 to your computer and use it in GitHub Desktop.
react-native save image
import React from 'react';
import { StyleSheet, Button, View, SafeAreaView, Text, Alert } from 'react-native';
import { WebView } from 'react-native-webview';
import * as MediaLibrary from 'expo-media-library';
import * as FileSystem from 'expo-file-system';
const App = () => {
// save image
const SaveToPhone = async (imagedata: string) => {
// get the base64 image string
const base64Code = imagedata.split('data:image/png;base64,')[1];
// create the image file
const filename = FileSystem.documentDirectory + 'receipt.png';
await FileSystem.writeAsStringAsync(filename, base64Code, {
encoding: FileSystem.EncodingType.Base64
});
const permission = await MediaLibrary.requestPermissionsAsync();
if (permission.granted) {
try {
// save the image
await MediaLibrary.saveToLibraryAsync(filename);
} catch (error) {
console.log(error);
}
} else {
console.log('Need Storage permission to save file');
}
};
const handleOnMessage = (event) => {
if (event && event.nativeEvent && event.nativeEvent.data) {
const data = JSON.parse(event.nativeEvent.data);
if (data.type === 'download') {
SaveToPhone(data.imagedata);
}
}
};
return (
<SafeAreaView style={styles.container}>
<View>
<Text style={styles.title}> TEST WESTERN UNION </Text>
<Button title="BUTTON TEST" onPress={() => Alert.alert('Button pressed')} />
</View>
<WebView onMessage={handleOnMessage} source={{ uri: 'https://checkout-western-union.dingdev.com/' }} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
marginHorizontal: 16
},
title: {
textAlign: 'center',
marginVertical: 8
},
fixToText: {
flexDirection: 'row',
justifyContent: 'space-between'
},
separator: {
marginVertical: 8,
borderBottomColor: '#737373',
borderBottomWidth: StyleSheet.hairlineWidth
}
});
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment