Reputation: 41
i'm completly new to react and react native too, but i'm trying to learn it.
I'm having a problem when i try to save picture to my phone gallery
So, i'm importing
import { MediaLibrary } from 'expo-media-library'
also i'm usigng states
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [cameraRef, setCameraRef] = useState(null)
and here all works fine except saving the photo
<TouchableOpacity style={{alignSelf: 'center'}} onPress={async() => {
if(cameraRef){
let photo = await cameraRef.takePictureAsync();
console.log('photo', photo);
MediaLibrary.saveToLibraryAsync(photo.uri)
}
}}>
in my console log i see the object
photo Object {
"height": 4156,
"uri": "file:///var/mobile/Containers/Data/Application/B7CCEDB6-DFC5-4898-BD70-B2FF1159FC1B/Library/Caches/ExponentExperienceData/%2540anonymous%252Ftest-5bfa90d8-12e9-44fe-a19d-69bb5eeb74b9/Camera/D783C734-29B9-489B-9798-A0737388E93C.jpg",
"width": 2376,
}
But i'm not able to find a way to save it to camera roll, i'm always getting this error
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_expoMediaLibrary.MediaLibrary.saveToLibraryAsync')]
Any help would be appreciate
R.
Upvotes: 1
Views: 5438
Reputation: 380
For me the problem was I followed the docs
https://docs.expo.dev/versions/latest/sdk/media-library/
and requested permissions:
if (permissionResponse.status !== 'granted') {
await requestPermission();
}
According to this github issue from expo team https://github.com/expo/expo/issues/9027
You don't need to ask for permission here.
So it seems the documentation should get updated
When I deleted asking for permissions, MediaLibrary.saveToLibraryAsync()
asks for permission by itself and allows saving videos to my camera roll.
Upvotes: 0
Reputation: 66
This was happening due to import issue.
// Change from this
import { MediaLibrary } from 'expo-media-library';
// To this
import * as MediaLibrary from 'expo-media-library';
This was answered in below thread. Mentioning here because if someone may come across this issue again.
Upvotes: 0
Reputation: 81
I think you're getting undefined object error with promise since you did not also concerned MediaLibrary.saveToLibraryAsync()
with await
.
You should maybe put MediaLibrary.saveToLibraryAsync()
with await
too just like you did on takePictureAsync() since it is a async function.
let photo = await cameraRef.takePictureAsync();
console.log('photo', photo);
await MediaLibrary.saveToLibraryAsync(photo.uri);
Just an assumption, hope it will help you to solve it.
Upvotes: 5