Giter VIP home page Giter VIP logo

react-native-gallery-manager's Introduction

Gallery Manager

Gallery manager for iOS and Android

Installation

npm install --save react-native-gallery-manager

or

yarn add react-native-gallery-manager

and then

react-native link

NOTE: If you are using CameraRoll from react-native, you have to unlink it before using this library

Issues

  • If the image is not being shown in Android try the following
    • increase fresco memory
    • resizeMethod='resize' to the Image component
    • removeClippedSubviews={true} to ScrollView (FlatList, SectionList)
    • android:largeHeap="true" to the android manifest.xml in the application section (I dont recommend that but, you got to do, what you got to do....)

#10569 #13600 #10470

Usage

import GalleryManager from 'react-native-gallery-manager';

Methods and Responses

Get Assets

GalleryManager.getAssets({
    type: 'all',             
    startFrom: 0,
}).then((response) => {

}).catch((err) => {
    // no rejects are defined currently on iOS
})
Props Type Default Notes
type String 'all' Type of the asset returned, can be 'image', 'video', 'all'
limit Number 10 how many asset to return in one call
startFrom Number 0 From which index to start
albumName String Set the name of the album from which you want assets (Optional)
Response
{
   assets:[
      {
         type:'image',
         uri:'file:///storage/emulated/0/Download/ylo6z7D.jpg',
         id:38,
         filename:'ylo6z7D.jpg',
         width:3456,
         height:1944,
         creationDate:'1517064428',
         duration:0,
         mimeType:'image/jpeg'
      },
      ...
   ],
   totalAssets:7,
   next:7,
   hasMore:false
}

Get Albums

GalleryManager.getAlbums().then((response) => {

}).catch((err) => {
    // no rejects are defined currently on iOS
})
Response
{ 
    albums: 
        [ 
            { 
            	assetCount: 616, title: 'WhatsApp' 
            },
            { 
            	assetCount: 6, title: 'Instagram' 
            },
            { 
            	assetCount: 1, title: 'Twitter' 
            },
            ...
        ],
    totalAlbums: 24 
}

Check Permission

GalleryManager.requestAuthorization(title, message).then((response) => {
    // response.isAuthorized = true || false
}).catch((err) => {
    
})
Props Type Default Notes
title String (Android) title of the dialog
message String (Android) message in the dialog

Convert Video (iOS only)

GalleryManager.convertVideo({
	id: '98F14DF6-3BF9-4D1B-A6E0-0A36A25AE377/L0/001',
	convertTo: 'm4v',
	quality: 'low'
}).then((response) => {
	console.log(response);
}).catch((err) => {
   console.log(err)
});
Props Type Default Notes
id String The id of the video asset
convertTo String Can be mpeg4, m4v or mov
quality String original Can be original, high, medium, low
Response
{ 
  mimeType: 'video/x-m4v',
  path: 'file:///Users/pentarex/Library/Developer/CoreSimulator/Devices/81873DB4-A220-4F60-88B8-87521BB231E6/data/Containers/Data/Application/91EE6566-4D04-4E33-9608-EDB06DA6C6D2/Documents/8DAEDFBC-9E16-442D-A98F-E145F429DA0B.m4v',
  filename: '8DAEDFBC-9E16-442D-A98F-E145F429DA0B.m4v',
  type: 'video',
  duration: 19.185833333333335 
}

The reason the library is returning the path of the file in this format is that the video can be send later to server with fetch library. If the url starts with assets-library:// not with file:// react-native will not send it.

Roadmap

Suggestions and forks are welcome

react-native-gallery-manager's People

Contributors

pentarex avatar robyweb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-gallery-manager's Issues

Suggestion: Convert the library to swift

Hi @pentarex

I have another suggestion - Better to convert this props from Objective -C to Swift to use latest features and better syntax and also Swift will be preferred language going forward for Apple.

I have wrote previously for my project code in swift and created a objc file bridge to expose method to RN.

Sample below:

// GalleryManager.swift

@objc func getAlbums(_ resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void{
    checkPhotoLibraryConfig()
    // check if the permission is set in info.plist
    let fetchOptions = PHFetchOptions()
    let albums: PHFetchResult<PHAssetCollection>? = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    let result = NSMutableArray();
    
    albums?.enumerateObjects({ (album, index, stop) in
      result.add(["title": album.localizedTitle as Any, "assetCount": album.estimatedAssetCount])
    })
    
    resolve(["albums": result, "totalAlbums": albums?.count ?? 0])
  }

// bridging header file
GalleryManager-Bridging-Header.h

// then exposing to RN here
GalleryManager-bridge.m

@interface RCT_EXTERN_MODULE(GalleryManager, NSObject)

RCT_EXTERN_METHOD(getAlbums: (RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)

@end

Let me know if its feasible to convert to Swift

Note - I did not test the above code - just for ref.

Crash: The RCTImageURLLoaders both reported that they can load the URL

The RCTImageURLLoaders <RNImageLoader: 0x604000010e30> and <RCTPhotoLibraryImageLoader: 0x604000010d00> both reported that they can load the URL assets-library://asset/asset.jpeg?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=jpeg, and have equal priority (0). This could result in non-deterministic behavior.

I need to use CameraRoll also - to save asset on device.

Error on GalleryManager.getAssets for Android only

React Native Environment Info:
System:
OS: macOS High Sierra 10.13.6
CPU: (4) x64 Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz
Memory: 32.97 MB / 8.00 GB
Shell: 5.3 - /bin/zsh
Binaries:
Node: 8.12.0 - ~/.nvm/versions/node/v8.12.0/bin/node
Yarn: 1.12.3 - /usr/local/bin/yarn
npm: 6.4.1 - ~/.nvm/versions/node/v8.12.0/bin/npm
SDKs:
iOS SDK:
Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3
Android SDK:
API Levels: 23, 25, 26, 27, 28
Build Tools: 27.0.3, 28.0.3
System Images: android-27 | Google Play Intel x86 Atom
IDEs:
Android Studio: 3.2 AI-181.5540.7.32.5056338
Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild
npmPackages:
react: 16.6.1 => 16.6.1
react-native: 0.57.5 => 0.57.5
npmGlobalPackages:
react-native-cli: 2.0.1

GalleryManager.requestAuthorization().then((result) => {
    console.warn(result);
    GalleryManager.getAssets({ type: 'all', limit: LIMIT, startFrom: assets.length }).then((response) => {
    console.warn(response);
    });
});

First console.warn shows isAuthorized: true
Then application fails. Error message is:

screen shot 2018-11-20 at 10 26 46

Is it possible to extend error message for debug purposes?

When scrolling down, the images are looping.

When I scroll down the gallery component, the next set of images are loaded from the gallery for a second but the component suddenly jumps to the start again, not loading other images.

GetAssets func sort order is not consistent

Hi @pentarex

Had another issue with sorting of images.
use of NSEnumerationConcurrent in below line is not maintaining proper descending order of creation date.

is there a way to keep it consistent.

[fetchResults enumerateObjectsAtIndexes:indexSet options:NSEnumerationConcurrent usingBlock:^(PHAsset * _Nonnull asset, NSUInteger index, BOOL * _Nonnull stop) {

Reverse order of getAssets

Hi @pentarex ,

I was wondering if it was possible to reverse the order in which the assets are being grabbed ie start from the last one (most recent in the gallery)?

autolinking

This library doesn't use autolinking, would it be possible to add this?

Suggestion: Compress video functionality

Hi

I have a feature suggestion for videos.

Provide functionality to convert video to 720p or 1080p and also compress video quality option and save local to app.

Useful for sharing and etc..

NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects

Hi

Got the below error when trying to run on iPad device with OS 10.3.3

'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects

I debugged the code and found that its failing when mimeType is null (when image is HEIC type the mimeType is null).

   [assets addObject:@{
                        @"type": [self getMediaType:([asset mediaType])],
                        @"width": @([asset pixelWidth]),
                        @"height": @([asset pixelHeight]),
                        @"filename": orgFilename ?: @"",
                        @"mimeType": mimeType,
                        @"id": [asset localIdentifier],
                        @"creationDate": [asset creationDate],
                        @"uri": [self buildAssetUri:[asset localIdentifier] extension:extension],
                        @"duration": @([asset duration])
                        }];
  }];

So the fix is to supply default when its null.
@"mimeType": mimeType ?: @""

Compress Video and Image for Android

Hi @pentarex This is library was very useful for me on iOS, now developing Android.

Do you know how compress video and Image on Android. i was able to do it on iOS.

Any code sample would appreciate.

How to load images faster

Hi @pentarex

I am loading images in paging of 40 images limit per request. When i test on iphone 6 its slow takes around a 1 sec to first each set of images to load.

I was testing other apps they are loaded instantly? like whatsapp

Is there anything we can to mimic to load faster?

TypeError: undefined is not an object (evaluating 'RNGalleryManager.requestAuthorization')

React Native Environment Info:
System:
OS: macOS High Sierra 10.13.6
CPU: (4) x64 Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz
Memory: 182.81 MB / 8.00 GB
Shell: 5.3 - /bin/zsh
Binaries:
Node: 8.12.0 - ~/.nvm/versions/node/v8.12.0/bin/node
Yarn: 1.12.3 - /usr/local/bin/yarn
npm: 6.4.1 - ~/.nvm/versions/node/v8.12.0/bin/npm
SDKs:
iOS SDK:
Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3
Android SDK:
API Levels: 23, 25, 26, 27, 28
Build Tools: 27.0.3, 28.0.3
System Images: android-27 | Google Play Intel x86 Atom
IDEs:
Android Studio: 3.2 AI-181.5540.7.32.5056338
Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild
npmPackages:
react: 16.6.1 => 16.6.1
react-native: 0.57.5 => 0.57.5
npmGlobalPackages:
react-native-cli: 2.0.1

GalleryManager.requestAuthorization().then((result) => {
    //
}).catch((err) => {
    console.error(err);
});

[Android] Crash when trying to get more assets and there are no more of them

Hi, when you get the assets on Android and reach the "end" of them, meaning that there are no more assets, the cursor is returning undefined instead of an empty array as it happens on iOS. This causes the app to crash if not handle properly so I think that the response should be the same as in iOS when there are no more assets.

• Android
First fetch returns 2 assets, which are the current assets in the device. Second call to the library causes a crash because the response is undefined.
screen shot 2018-05-24 at 16 05 31

• iOS
First fetch returns 1 asset, the only one available in the device. Second call returns empty array, so the app doesn't crash and everything works fine.
screen shot 2018-05-24 at 16 07 04

Suggestion: Add the whole file path

Right now, the asset object return an uri like assets-library://asset/asset.mp4?id=7ED0862F-75A0-4EDE-8096-0F5F695045C2&ext=mp4 is it possible to also retrieve the path like
file:///Users/pentarex/Library/Developer/CoreSimulator/Devices/81873DB4-A220-4F60-88B8-87521BB231E6/data/Containers/Data/Application/91EE6566-4D04-4E33-9608-EDB06DA6C6D2/Documents/8DAEDFBC-9E16-442D-A98F-E145F429DA0B.m4v to use it with other libraries?

Get albums with type ?

Hi this is great library,
Would be better if getAlbums provide with option like, i only want to get albums with only jpeg inside it.

Android crash: CursorIndexOutOfBoundsException

I'm getting this crash pretty consistently on Android in my pre-launch reports and also on a few production devices. Error handling doesn't seem to help.

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
	at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
	at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
	at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
	at android.database.CursorWrapper.getString(CursorWrapper.java:137)
	at org.pentarex.rngallerymanager.RNGalleryManagerModule.getAlbum(RNGalleryManagerModule.java:170)
	at org.pentarex.rngallerymanager.RNGalleryManagerModule.getAlbums(RNGalleryManagerModule.java:120)

Here is my code:

const { albumNames } = this.state;

GalleryManager.getAlbums().then( ( results ) => {
      const { albums } = results;
      if ( albums && albums.length > 0 ) {
        albums.forEach( ( album ) => {
          const { assetCount, title } = album;

          if ( assetCount > 0 ) {
            albumNames.push( {
              label: title,
              value: title
            } );
          }
        } );
      }

      this.setState( { albumNames } );
    } ).catch( () => {
      this.setState( { albumNames } );
    } );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.