Last active
August 18, 2019 20:19
-
-
Save libasoles/82a4be702717ed9ec05442cce9fa65d5 to your computer and use it in GitHub Desktop.
React Native save to cameraRoll draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Fragment, useState, useCallback, useRef, useEffect} from 'react'; | |
import {PermissionsAndroid, StyleSheet, Button, View, Text} from 'react-native'; | |
import {captureRef} from 'react-native-view-shot'; | |
import CameraRoll from '@react-native-community/cameraroll'; | |
function useCapture() { | |
const captureViewRef = useRef(null); | |
const [shouldAskForPermission, setShouldAskForPermission] = useState(false); | |
const [permissionGranted, setPermissionGranted] = useState(false); | |
useEffect(() => { | |
(async function askPermission() { | |
if (shouldAskForPermission && !permissionGranted) { | |
const isGranted = await PermissionsAndroid.request( | |
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, | |
); | |
if (isGranted === PermissionsAndroid.RESULTS.GRANTED) { | |
setPermissionGranted(true); | |
setShouldAskForPermission(false); | |
onCapture(); | |
} else if (isGranted === PermissionsAndroid.RESULTS.DENIED) { | |
console.log('Next time :('); | |
} else { | |
console.log('Oh no! :O'); | |
setShouldAskForPermission(false); | |
} | |
} | |
})(); | |
}, [ | |
onCapture, | |
shouldAskForPermission, | |
permissionGranted, | |
setPermissionGranted, | |
]); | |
const onCapture = useCallback(() => { | |
(async function onCapture() { | |
const canSaveToDevice = await PermissionsAndroid.check( | |
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, | |
); | |
if (!canSaveToDevice) { | |
setShouldAskForPermission(true); | |
setPermissionGranted(false); | |
return false; | |
} | |
captureRef(captureViewRef, { | |
format: 'jpg', | |
quality: 0.9, | |
}) | |
.then(uri => { | |
console.log('storing'); | |
CameraRoll.save(uri, {type: 'photo', album: 'Doaut'}).then( | |
console.log, | |
console.error, | |
); | |
}) | |
.catch(error => console.log('Oops, snapshot failed', error)); | |
})(); | |
}, []); | |
return { | |
captureViewRef, | |
onCapture, | |
}; | |
} | |
function App() { | |
const {captureViewRef, onCapture} = useCapture(); | |
return ( | |
<Fragment> | |
<Button onPress={onCapture} title="Save" /> | |
<View style={styles.capture} ref={captureViewRef}> | |
<Text style={styles.content}>Capture</Text> | |
</View> | |
</Fragment> | |
); | |
} | |
const styles = StyleSheet.create({ | |
capture: { | |
flex: 1, | |
backgroundColor: '#313131', | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
content: { | |
color: 'white', | |
fontSize: 40, | |
}, | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment