@@ -4,13 +4,18 @@ import { Platform } from 'react-native';
44
55import * as MediaLibrary from 'expo-media-library' ;
66
7+ const hasMediaPermission = ( response : MediaLibrary . PermissionResponse | null ) : boolean => {
8+ return response ?. granted ?? false ;
9+ } ;
10+
711export function useMediaLibrary ( ) {
812 const [ albums , setAlbums ] = useState < MediaLibrary . Album [ ] | null > ( null ) ;
913 const [ assets , setAssets ] = useState < MediaLibrary . Asset [ ] > ( [ ] ) ;
1014 const [ loading , setLoading ] = useState ( false ) ;
1115 const [ hasNextPage , setHasNextPage ] = useState ( false ) ;
1216 const [ permissionResponse , requestPermission ] = MediaLibrary . usePermissions ( ) ;
1317 const loadingRef = useRef ( false ) ;
18+ const hasRequestedPermission = useRef ( false ) ;
1419
1520 const fetchAlbums = useCallback (
1621 async ( options : MediaLibrary . AlbumsOptions = { includeSmartAlbums : true } ) => {
@@ -21,13 +26,19 @@ export function useMediaLibrary() {
2126
2227 try {
2328 let response = permissionResponse ;
24- if ( ! response || response . status !== 'granted' ) response = await requestPermission ( ) ;
29+ // Only request permission if we haven't already and user can be asked
30+ if ( ! hasMediaPermission ( response ) && ! hasRequestedPermission . current ) {
31+ if ( ! response || response . canAskAgain !== false ) {
32+ hasRequestedPermission . current = true ;
33+ response = await requestPermission ( ) ;
34+ }
35+ }
2536
26- if ( response ?. granted ) {
37+ if ( hasMediaPermission ( response ) ) {
2738 const fetchedAlbums = await MediaLibrary . getAlbumsAsync ( options ) ;
2839 setAlbums ( fetchedAlbums ) ;
2940 } else {
30- alert ( 'Permission denied ') ;
41+ console . warn ( 'Media library permission not granted ') ;
3142 }
3243 } catch ( error ) {
3344 console . error ( 'Error fetching albums:' , error ) ;
@@ -46,11 +57,15 @@ export function useMediaLibrary() {
4657 setLoading ( true ) ;
4758 try {
4859 let response = permissionResponse ;
49- if ( ! response || response . status !== 'granted' ) {
50- response = await requestPermission ( ) ;
60+ // Only request permission if we haven't already and user can be asked
61+ if ( ! hasMediaPermission ( response ) && ! hasRequestedPermission . current ) {
62+ if ( ! response || response . canAskAgain !== false ) {
63+ hasRequestedPermission . current = true ;
64+ response = await requestPermission ( ) ;
65+ }
5166 }
5267
53- if ( response ?. granted ) {
68+ if ( hasMediaPermission ( response ) ) {
5469 const result = await MediaLibrary . getAssetsAsync ( options ) ;
5570
5671 // On iOS, convert ph:// URIs to file:// URIs for React Native Image component
0 commit comments