React native camera roll not returning any images in getPhotos and getAlbums method in ios

1.9k Views Asked by At

I am currently using @react-native-community/cameraroll currently and i am trying to get images and albums on my ios device. The following is the code I tried

                    CameraRoll.getPhotos({})
                        .then((res) => {
                            console.log("result 1", res)
                        }).catch((error) => { })

                    CameraRoll.getAlbums({})
                        .then((res) => {
                            console.log("result 2", res)
                        })
                        .catch((error) => {
                            console.log(error);
                        });

result 1 and result 2 give the following result

result 1 {"edges": [], "page_info": {"has_next_page": false}}
result 2 []

Any help would be appreciated. The same code works well on Android.

2

There are 2 best solutions below

3
On

I tried with a lot of combinations and the one below worked for the ios device -

CameraRoll.getPhotos({ first: 5000, assetType: 'Photos' })
            .then((result) => {
                const tempBuckets = [];
                var edgesArr = result.edges;
            }).catch((error) => { })

The result here contains an edges array that has all the images and their respective properties. The count '5000' is an arbitrary number i have used, without which the result array obtained was empty.

0
On

the solution is to add permission before request like

async function hasAndroidPermission() {
    const permission = 
   PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
  
    const hasPermission = await PermissionsAndroid.check(permission);
    if (hasPermission) {
      return true;
    }
  
    const status = await PermissionsAndroid.request(permission);
    return status === 'granted';
  }

and use like this

const Gallery = async () =>{
    if (Platform.OS === "android" && !(await hasAndroidPermission())) {
        return;
      }
    CameraRoll.getAlbums({assetType: "Photos", albumType: "All"})
      .then((r:any) => {
        console.log("images-->",r)
      })
      .catch((err:any) => {
         //Error Loading Images
         console.log("err->",err)
      });
   

}