0. 설치
npx expo install expo-media-library
config plugin이 프로젝트에 있는 경우
{
"expo": {
"plugins": [
[
"expo-media-library",
{
"photosPermission": "Allow $(PRODUCT_NAME) to access your photos.",
"savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.",
"isAccessMediaLocationEnabled": true
}
]
]
}
}
1. 앨범 권한
앨범 접근 권한을 묻고, 접근 권한을 얻으면 앨범 컴포넌트로 이동
const { status: albumStatus } = await MediaLibrary.requestPermissionsAsync();
if (albumStatus === 'granted') {
navigation.navigate('AlbumScreen', {
nextScreen: 'MealtimeScreen',
});
} else {
Alert.alert('앨범 접근 허용은 필수입니다.');
}
2. 앨범에서 선택
AlbumScreen.js
import * as MediaLibrary from 'expo-media-library';
//앨범 사진들
const [photos, setPhotos] = useState([])
//사진 중 택한것
const [chosenPhoto, setChosenPhoto] = useState(null)
//맨처음 실행
useEffect(() => {
getPhotos();
}, [])
const getPhotos = async () => {
const { assets } = await MediaLibrary.getAssetsAsync();
setPhotos([...assets])
};
const renderItem = ({ item }) => {
return (
<Pressable onPress={() => setChosenPhoto(item)} style={styles.imageView} >
<Image source={{ uri: item.uri }} style={styles.image} resizeMode="cover" />
</Pressable>
);
};
return photos.length !== 0 && (
<RootView viewStyle={styles.container}>
<FlatList
data={photos}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={3}
showsVerticalScrollIndicator="false"
/>
</RootView>
)
3. 앨범 사진 프리뷰 제공 및 옵션
AlbumScreen.js
//다시찍기 클릭시 호출되는 함수
const reChoosePictureHandler = () => {
setChosenPhoto(null)
}
//완료 클릭시 호출되는 함수
const uploadPictureHandler = () => {
let params = {};
navigation.navigate(nextScreen, params)
}
return photos.length !== 0 && (
//chosenPhoto ? (...) : (...) 를 통해 앨범 사진 클릭 시 프리뷰 제공 및 옵션 제공
chosenPhoto ? (
<RootView>
<Image source={{ uri: chosenPhoto.uri }} style={styles.album} />
<View style={styles.touchView}>
<TouchableOpacity activeOpacity={0.6} onPress={reChoosePictureHandler}>
<Text style={styles.text}>다시선택</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.6} onPress={uploadPictureHandler}>
<Text style={styles.text}>완료</Text>
</TouchableOpacity>
</View>
</RootView>
) : (
<RootView viewStyle={styles.container}>
<FlatList
data={photos}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={3}
showsVerticalScrollIndicator="false"
/>
</RootView>
)
)
* 참조
https://docs.expo.dev/versions/latest/sdk/media-library/
MediaLibrary
A library that provides access to the device's media library.
docs.expo.dev
'Framework > React Native' 카테고리의 다른 글
[RN][Expo] Semi-Calories 개발 도움됐던 Document 정리 (0) | 2023.08.25 |
---|---|
[RN][Expo] Axios 를 이용해 API(Spring)와 통신 (0) | 2023.08.13 |
[RN][Expo] expo-media-library 앨범 사진 onEndReached로 계속 가져오기 (0) | 2023.08.01 |
[RN][Expo] expo-camera 적용 (0) | 2023.08.01 |
[RN][Expo] 절대경로 설정 (0) | 2023.07.05 |