Reputation: 21
my function:
async function takePhotoNStore(){
if(cameraRef){
let picture = await cameraRef.current.takePictureAsync();
const asset = await MediaLibrary.createAssetAsync(picture.uri);
await MediaLibrary.createAlbumAsync('Expo', asset, false);
}
}
I'm trying to create one album named "Expo" but it keeps creating multiple "Expo" album every time I take a new picture.
Upvotes: 2
Views: 3627
Reputation: 1
saveFile = async (fileUri) => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
const cachedAsset = await MediaLibrary.createAssetAsync(fileUri);
const albumName = "xyz';
const album = await MediaLibrary.getAlbumAsync(albumName)
if(album){
await MediaLibrary.addAssetsToAlbumAsync([cachedAsset], album, false);
}else{
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync(albumName, asset);
}
}
};
Upvotes: 0
Reputation: 254
For future reference
_saveToCameraRollAsync = async () => {
try {
let result = await captureRef(this.pageView, {
format: 'png',
quality: 0.9
});
const cachedAsset = await MediaLibrary.createAssetAsync(result);
// saved the asset uri
const album = await MediaLibrary.getAlbumAsync('GWA');
// check if the album if exist if return null you need to create an album.
if (album === null) {
// insert an album name with image
const asset = await MediaLibrary.createAssetAsync(result);
MediaLibrary.createAlbumAsync('GWA', asset)
.then(() => {
console.log('Album created!');
Alert.alert('Image has been saved')
this.setState({ cameraRollUri: asset });
})
.catch(error => {
Alert.alert(`Opps there's something wrong`)
console.log('err', error);
});
} else {
// if album exist asset added
let assetAdded = await MediaLibrary.addAssetsToAlbumAsync(
[cachedAsset],
album,
false
);
if (assetAdded === true) {
this.getAssetFromAlbum(album);
} else {
console.log("ASSET ADD ERROR");
}
}
}
catch (snapshotError) {
console.error(snapshotError);
}
};
getAssetFromAlbum = async album => {
//function
const assetResult = await MediaLibrary.getAssetsAsync({
first: 1,
album: album,
sortBy: MediaLibrary.SortBy.creationTime,
});
const asset = await assetResult.assets[0];
this.setState({ image_uri: asset.uri });
};
Upvotes: 0
Reputation: 513
You need to check if the album already exists with :
MediaLibrary.getAlbumAsync(albumName)
If this is the case, you can add your assets with :
MediaLibrary.addAssetsToAlbumAsync(assets, album, copyAssets)
If not, create it like you did.
You won't have any duplication! :)
Upvotes: 2