I am developing an iOS/Android app with React Native and I am getting an error on Android.
I am using the expo-image-picker library https://docs.expo.dev/versions/latest/sdk/imagepicker/
This is the code which works perfectly on iOS:
const prepareResult = await ImagePicker.launchImageLibraryAsync({
quality: 0.5,
capture: true,
aspect: [4, 3],
allowsEditing: true,
allowsMultipleSelection: false,
mediaTypes: ImagePicker.MediaTypeOptions.Images,
});
const androidResult = await ImagePicker.getPendingResultAsync();
const result = androidResult?.length ? androidResult[0] : prepareResult;
if (!result.cancelled) {
const localUri = result.uri;
const filename = localUri.split("/").pop();
const match = filename ? /\.(\w+)$/.exec(filename) : "";
const type = match ? `image/${match[1]}` : `image`;
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
fetch(`${API}/uploadAvatar`, {
method: "POST",
headers: {
Authorization: bearer,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
body: formData,
})
.then((response) => response.json())
.then((json) => {
setImage(json.file);
})
.catch((err) => {
console.log({ err });
Alert.alert("There was an error uploading your profile picture.");
});
}
On Android after I crop the image, it goes straight to the .catch method without even going through any of the .then methods.
I checked this https://docs.expo.dev/versions/latest/sdk/imagepicker/#imagepickergetpendingresultasync which contains a note:
Note: Make sure that you handle MainActivity destruction on Android. See ImagePicker.getPendingResultAsync.
Any ideas about this error?
If you're not an expo project, but a react-native project,
It is recommended to use a react-native-image-cropicker.
import ImagePicker from 'react-native-image-crop-picker';
//select image
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log(image);
});
//select from Camera
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true,
}).then(image => {
console.log(image);
});