Installations
npm install react-native-smart-album-camera-roll
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
20.6.0
NPM Version
9.8.1
Score
41.8
Supply Chain
56.6
Quality
66.1
Maintenance
50
Vulnerability
93.8
License
Releases
Contributors
Unable to fetch Contributors
Languages
Java (26.3%)
Objective-C++ (24.5%)
TypeScript (23.03%)
Objective-C (14.81%)
JavaScript (6.74%)
Kotlin (2.39%)
Ruby (2.22%)
Developer
react-native-cameraroll
Download Statistics
Total Downloads
1,104
Last Day
1
Last Week
6
Last Month
28
Last Year
314
GitHub Statistics
974 Stars
489 Commits
443 Forks
16 Watching
14 Branches
150 Contributors
Bundle Size
3.39 kB
Minified
1.34 kB
Minified + Gzipped
Package Meta Information
Latest Version
6.0.5
Package Id
react-native-smart-album-camera-roll@6.0.5
Unpacked Size
341.56 kB
Size
129.66 kB
File Count
75
NPM Version
9.8.1
Node Version
20.6.0
Publised On
15 Sept 2023
Total Downloads
Cumulative downloads
Total Downloads
1,104
Last day
-90%
1
Compared to previous day
Last week
-40%
6
Compared to previous week
Last month
180%
28
Compared to previous month
Last year
-60.3%
314
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
1
Dev Dependencies
25
react-native-smart-album-camera-roll
Getting started
$ npm install react-native-smart-album-camera-roll --save
Mostly automatic installation
$ react-native link react-native-smart-album-camera-roll && npx pod-install
Manual installation
iOS
- In XCode, in the project navigator, right click
Libraries
âžœAdd Files to [your project's name]
- Go to
node_modules
âžœreact-native-smart-album-camera-roll
and addRNCCameraroll.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRNCCameraroll.a
to your project'sBuild Phases
âžœLink Binary With Libraries
- Run your project (
Cmd+R
)<
Android
- Open up
android/app/src/main/java/[...]/MainApplication.java
(Auto link, ^RN0.69 does not required)
- Add
import com.reactnativecommunity.cameraroll.CameraRollPackage;
to the imports at the top of the file - Add
new CameraRollPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':@react-native-camera-roll_camera-roll' project(':@react-native-camera-roll_camera-roll').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-album-camera-roll/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:implementation project(':@react-native-camera-roll_camera-roll')
Migrating from the core react-native
module
This module was created when the CameraRoll was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:
1import { CameraRoll } from "react-native";
to:
1import { CameraRoll } from "react-native-smart-album-camera-roll";
Usage
CameraRoll
provides access to the local camera roll or photo library.
Permissions
iOS
The user's permission is required in order to access the Camera Roll on devices running iOS 10 or later. Add the NSPhotoLibraryUsageDescription
key in your Info.plist
with a string that describes how your app will use this data. This key will appear as Privacy - Photo Library Usage Description
in Xcode.
If you are targeting devices running iOS 11 or later, you will also need to add the NSPhotoLibraryAddUsageDescription
key in your Info.plist
. Use this key to define a string that describes how your app will use this data. By adding this key to your Info.plist
, you will be able to request write-only access permission from the user. If you try to save to the camera roll without this permission, your app will exit.
Android
Permission is required to read and write to the external storage.
On Expo, follow the guide here for requesting the permission.
On react-native-cli or ejected apps, adding the following lines will add the capability for the app to request the permission. Find more info on Android Permissions here.
1<manifest> 2... 3 <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> 4 <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> 5 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" 6 android:maxSdkVersion="32" /> 7 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 8... 9<application>
Then you have to explicitly ask for the permission
1import { PermissionsAndroid, Platform } from "react-native"; 2import { CameraRoll } from "react-native-smart-album-camera-roll"; 3 4async function hasAndroidPermission() { 5 const getCheckPermissionPromise = () => { 6 if (Platform.Version >= 33) { 7 return Promise.all([ 8 PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES), 9 PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO), 10 ]).then( 11 ([hasReadMediaImagesPermission, hasReadMediaVideoPermission]) => 12 hasReadMediaImagesPermission && hasReadMediaVideoPermission, 13 ); 14 } else { 15 return PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE); 16 } 17 }; 18 19 const hasPermission = await getCheckPermissionPromise(); 20 if (hasPermission) { 21 return true; 22 } 23 const getRequestPermissionPromise = () => { 24 if (Platform.Version >= 33) { 25 return PermissionsAndroid.requestMultiple([ 26 PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES, 27 PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO, 28 ]).then( 29 (statuses) => 30 statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES] === 31 PermissionsAndroid.RESULTS.GRANTED && 32 statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO] === 33 PermissionsAndroid.RESULTS.GRANTED, 34 ); 35 } else { 36 return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE).then((status) => status === PermissionsAndroid.RESULTS.GRANTED); 37 } 38 }; 39 40 return await getRequestPermissionPromise(); 41} 42 43async function savePicture() { 44 if (Platform.OS === "android" && !(await hasAndroidPermission())) { 45 return; 46 } 47 48 CameraRoll.save(tag, { type, album }) 49};
Methods
Reference
Methods
save()
1CameraRoll.save(tag, { type, album })
Saves the photo or video to the photo library.
On Android, the tag must be a local image or video URI, such as "file:///sdcard/img.png"
.
On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).
If the tag has a file extension of .mov or .mp4 (lower or uppercase), it will be inferred as a video. Otherwise it will be treated as a photo. To override the automatic choice, you can pass an optional type
parameter that must be one of 'photo' or 'video'.
It allows to specify a particular album you want to store the asset to when the param album
is provided.
On Android, if no album is provided, DCIM directory is used, otherwise PICTURE or MOVIES directory is used depending on the type
provided.
Returns a Promise which will resolve with the new URI.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
tag | string | Yes | See above. |
type | enum('photo', 'video') | No | Overrides automatic detection based on the file extension. |
album | string | No | The album to save to |
getAlbums()
1CameraRoll.getAlbums(params);
Returns a Promise with a list of albums
Parameters:
assetType
: {string} : Specifies filter on asset type. Valid values are:All
// defaultVideos
Photos
Returns:
Array of Album
object
- title: {string}
- count: {number}
getPhotos()
1CameraRoll.getPhotos(params);
Returns a Promise with photo identifier objects from the local camera roll of the device matching shape defined by getPhotosReturnChecker
.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
params | object | Yes | Expects a params with the shape described below. |
first
: {number} : The number of photos wanted in reverse order of the photo application (i.e. most recent first for SavedPhotos). Required.after
: {string} : A cursor that matchespage_info { end_cursor }
returned from a previous call togetPhotos
. Note that using this will reduce performance slightly on iOS. An alternative is just using thefromTime
andtoTime
filters, which have no such impact.groupTypes
: {string} : Specifies which group types to filter the results to. Valid values are:Album
All
// defaultEvent
Faces
Library
PhotoStream
SavedPhotos
groupName
: {string} : Specifies filter on group names, like 'Recent Photos' or custom album titles.assetType
: {string} : Specifies filter on asset type. Valid values are:All
Videos
Photos
// default
mimeTypes
: {Array} : Filter by mimetype (e.g. image/jpeg). Note that using this will reduce performance slightly on iOS.fromTime
: {number} : Filter by creation time with a timestamp in milliseconds. This time is exclusive, so we'll select all photos withtimestamp > fromTime
.toTime
: {number} : Filter by creation time with a timestamp in milliseconds. This time is inclusive, so we'll select all photos withtimestamp <= toTime
.include
: {Array} : Whether to include some fields that are slower to fetchfilename
: Ensuresimage.filename
is available in each node. This has a large performance impact on iOS.fileSize
: Ensuresimage.fileSize
is available in each node. This has a large performance impact on iOS.fileExtension
: Ensuresimage.fileExtension
is available in each node.location
: Ensureslocation
is available in each node. This has a large performance impact on Android.imageSize
: Ensuresimage.width
andimage.height
are available in each node. This has a small performance impact on Android.playableDuration
: Ensuresimage.playableDuration
is available in each node. This has a medium peformance impact on Android.orientation
: Ensuresimage.orientation
is available in each node. This has a small peformance impact on Android. Android only
Returns a Promise which when resolved will be of the following shape:
edges
: {Array} An array of node objects node
: {object} An object with the following shape:type
: {string}subTypes
: {Array} : An array of subtype strings (see SubTypes
type). Always [] on Android.group_name
: {string}image
: {object} : An object with the following shape:uri
: {string}filename
: {string | null} : Only set if theinclude
parameter containsfilename
extension
: {string | null} : Only set if theinclude
parameter containsfileExtension
height
: {number | null} : Only set if theinclude
parameter containsimageSize
width
: {number | null} : Only set if theinclude
parameter containsimageSize
fileSize
: {number | null} : Only set if theinclude
parameter containsfileSize
playableDuration
: {number | null} : Only set for videos if theinclude
parameter containsplayableDuration
. Will be null for images.orientation
: {number | null} : Only set for images if theinclude
parameter containsorientation
. Android only
timestamp
: {number}modificationTimestamp
: {number}location
: {object | null} : Only set if theinclude
parameter containslocation
. An object with the following shape:latitude
: {number}longitude
: {number}altitude
: {number}heading
: {number}speed
: {number}
page_info
: {object} : An object with the following shape:has_next_page
: {boolean}start_cursor
: {string}end_cursor
: {string}
limited
: {boolean | undefined} : true if the app can only access a subset of the gallery pictures (authorization isPHAuthorizationStatusLimited
), false otherwise (iOS only)
Example
Loading images:
1_handleButtonPress = () => { 2 CameraRoll.getPhotos({ 3 first: 20, 4 assetType: 'Photos', 5 }) 6 .then(r => { 7 this.setState({ photos: r.edges }); 8 }) 9 .catch((err) => { 10 //Error Loading Images 11 }); 12 }; 13render() { 14 return ( 15 <View> 16 <Button title="Load Images" onPress={this._handleButtonPress} /> 17 <ScrollView> 18 {this.state.photos.map((p, i) => { 19 return ( 20 <Image 21 key={i} 22 style={{ 23 width: 300, 24 height: 100, 25 }} 26 source={{ uri: p.node.image.uri }} 27 /> 28 ); 29 })} 30 </ScrollView> 31 </View> 32 ); 33}
Loading images with listeners and refetchs:
1import { CameraRoll, cameraRollEventEmitter } from 'react-native-smart-album-camera-roll'; 2 3import { useCallback, useEffect, useState } from 'react'; 4 5import { AppState, EmitterSubscription } from 'react-native'; 6 7interface GalleryOptions { 8 pageSize: number; 9 mimeTypeFilter?: Array<string>; 10} 11 12interface GalleryLogic { 13 photos?: ImageDTO[]; 14 loadNextPagePictures: () => void; 15 isLoading: boolean; 16 isLoadingNextPage: boolean; 17 isReloading: boolean; 18 hasNextPage: boolean; 19} 20 21const supportedMimeTypesByTheBackEnd = [ 22 'image/jpeg', 23 'image/png', 24 'image/heif', 25 'image/heic', 26 'image/heif-sequence', 27 'image/heic-sequence', 28]; 29 30export const useGallery = ({ 31 pageSize = 30, 32 mimeTypeFilter = supportedMimeTypesByTheBackEnd, 33}: GalleryOptions): GalleryLogic => { 34 const [isLoading, setIsLoading] = useState(false); 35 const [isReloading, setIsReloading] = useState(false); 36 const [isLoadingNextPage, setIsLoadingNextPage] = useState(false); 37 const [hasNextPage, setHasNextPage] = useState(false); 38 const [nextCursor, setNextCursor] = useState<string>(); 39 const [photos, setPhotos] = useState<ImageDTO[]>(); 40 41 const loadNextPagePictures = useCallback(async () => { 42 try { 43 nextCursor ? setIsLoadingNextPage(true) : setIsLoading(true); 44 const { edges, page_info } = await CameraRoll.getPhotos({ 45 first: pageSize, 46 after: nextCursor, 47 assetType: 'Photos', 48 mimeTypes: mimeTypeFilter, 49 ...(isAndroid && { include: ['fileSize', 'filename'] }), 50 }); 51 const photos = convertCameraRollPicturesToImageDtoType(edges); 52 setPhotos((prev) => [...(prev ?? []), ...photos]); 53 54 setNextCursor(page_info.end_cursor); 55 setHasNextPage(page_info.has_next_page); 56 } catch (error) { 57 console.error('useGallery getPhotos error:', error); 58 } finally { 59 setIsLoading(false); 60 setIsLoadingNextPage(false); 61 } 62 }, [mimeTypeFilter, nextCursor, pageSize]); 63 64 const getUnloadedPictures = useCallback(async () => { 65 try { 66 setIsReloading(true); 67 const { edges, page_info } = await CameraRoll.getPhotos({ 68 first: !photos || photos.length < pageSize ? pageSize : photos.length, 69 assetType: 'Photos', 70 mimeTypes: mimeTypeFilter, 71 // Include fileSize only for android since it's causing performance issues on IOS. 72 ...(isAndroid && { include: ['fileSize', 'filename'] }), 73 }); 74 const newPhotos = convertCameraRollPicturesToImageDtoType(edges); 75 setPhotos(newPhotos); 76 77 setNextCursor(page_info.end_cursor); 78 setHasNextPage(page_info.has_next_page); 79 } catch (error) { 80 console.error('useGallery getNewPhotos error:', error); 81 } finally { 82 setIsReloading(false); 83 } 84 }, [mimeTypeFilter, pageSize, photos]); 85 86 useEffect(() => { 87 if (!photos) { 88 loadNextPagePictures(); 89 } 90 }, [loadNextPagePictures, photos]); 91 92 useEffect(() => { 93 const subscription = AppState.addEventListener('change', async (nextAppState) => { 94 if (nextAppState === 'active') { 95 getUnloadedPictures(); 96 } 97 }); 98 99 return () => { 100 subscription.remove(); 101 }; 102 }, [getUnloadedPictures]); 103 104 useEffect(() => { 105 let subscription: EmitterSubscription; 106 if (isAboveIOS14) { 107 subscription = cameraRollEventEmitter.addListener('onLibrarySelectionChange', (_event) => { 108 getUnloadedPictures(); 109 }); 110 } 111 112 return () => { 113 if (isAboveIOS14 && subscription) { 114 subscription.remove(); 115 } 116 }; 117 }, [getUnloadedPictures]); 118 119 return { 120 photos, 121 loadNextPagePictures, 122 isLoading, 123 isLoadingNextPage, 124 isReloading, 125 hasNextPage, 126 }; 127};
deletePhotos()
1CameraRoll.deletePhotos([uri]);
Requests deletion of photos in the camera roll.
On Android, the uri must be a local image or video URI, such as "file:///sdcard/img.png"
.
On iOS, the uri can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI. The user is presented with a dialog box that shows them the asset(s) and asks them to confirm deletion. This is not able to be bypassed as per Apple Developer guidelines.
Returns a Promise which will resolve when the deletion request is completed, or reject if there is a problem during the deletion. On iOS the user is able to cancel the deletion request, which causes a rejection, while on Android the rejection will be due to a system error.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
uri | string | Yes | See above. |
iosGetImageDataById()
1CameraRoll.iosGetImageDataById(internalID, true);
Parameters:
Name | Type | Required | Description |
---|---|---|---|
internalID | string | Yes | Ios internal ID 'PH://xxxx'. |
convertHeic | boolean | False | Whether to convert or not to JPEG image. |
Upload photo/video with iosGetImageDataById
method
1 2try { 3// uri 'PH://xxxx' 4const fileData = await CameraRoll.iosGetImageDataById(uri); 5if (!fileData?.node?.image?.filepath) return undefined; 6const uploadPath = imageData.node.image.filepath; // output should be file://... 7// fetch or ReactNativeBlobUtil.fetch to upload 8} 9catch (error) {} 10
useCameraRoll()
useCameraRoll
is a utility hooks for the CameraRoll module.
1import React, {useEffect} from 'react'; 2import {Button} from 'react-native'; 3import {useCameraRoll} from "react-native-smart-album-camera-roll"; 4 5function Example() { 6 const [photos, getPhotos, save] = useCameraRoll(); 7 8 return <> 9 <Button title='Get Photos' onPress={() => getPhotos()}>Get Photos</Button> 10 { 11 photos.map((photo, index) => /* render photos */) 12 } 13 </>; 14};
Known issues
IOS
If you try to save media into specific album without asking for read and write permission then saving will not work, workaround is to not precice album name for IOS if you don't want to request full permission (Only ios >= 14).
![Empty State](/_next/static/media/empty.e5fae2e5.png)
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
7 commit(s) and 5 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
- Info: project has a license file: LICENCE:0
- Info: FSF or OSI recognized license: MIT License: LICENCE:0
Reason
binaries present in source code
Details
- Warn: binary detected: FabricExample/android/gradle/wrapper/gradle-wrapper.jar:1
- Warn: binary detected: android/gradle/wrapper/gradle-wrapper.jar:1
- Warn: binary detected: example/android/gradle/wrapper/gradle-wrapper.jar:1
Reason
Found 8/22 approved changesets -- score normalized to 3
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/stale.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/stale.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/react-native-cameraroll/react-native-cameraroll/stale.yml/master?enable=pin
- Info: 0 out of 1 GitHub-owned GitHubAction dependencies pinned
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 19 are checked with a SAST tool
Reason
11 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-7mhc-prgv-r3q4
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-v8v8-6859-qxm4
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-g4rg-993r-mgx7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
3.4
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More