React native pictures saved to a local album (iOS Android)

Source: Internet
Author: User
Tags mongodb postgresql redis

React native pictures saved to a local album (iOS Android) 


1, requirements analysis

(1),react native Save the network image to the album, iOS can be used with RN cameraroll perfect solution, but the Android side does not support to save pictures from the network.



(2), save only one picture to the local album (such as generated invitation card payment code, etc.)



2, introduction with iOS Simple Configuration 

2.1 introduction Savetocameraroll (tag, type?) Method Introduction

 (1) This is a static method of Cameraroll, the function is to save a picture to the album.

 (2) The parameter tag is the address of the picture, which is the string type. The content varies depending on the device:

On Android: Tag is a local address, for example: "File:///sdcard/img.png"
On IOS: Tag can be one of the URLs, assets-library, and memory images.

(3) The parameter type is not required, and the optional value is ' photo ' or ' video '. Used to indicate whether a picture or a video is stored. If not specified, the program will also be judged by its suffix. (End with. mov or. mp4 for video, others as pictures)

 2.2 cameraroll API iOS link configuration 


The first step

Add Cameraroll Library (node_modules/react-native/Libraries/Cameraroll/rctcameraroll.xcodeproj) to Xcode'sLibrariesin Group 

The second step

Put the rctcameraroll.xcodeproj under theProductsIn the folder, drag the static library file (. A file) to the Xcode general--linked frameworkslibraries.


The third step

Configure access to the album, and if you do not configure the Privacy-photo Library additions usage description to Info.plist, there will be a flashback situation. Add the following in Info.plist:


1 <key>NSPhotoLibraryAddUsageDescription</key>
2 <string> use album </string>
3 <key>NSPhotoLibraryUsageDescription</key>
4 <string> use album </string> 


Android has direct access to the Cameraroll API








 
 
1 import { Platform, CameraRoll } from 'react-native';
2 import RNFS from 'react-native-fs';

3, application example

 3.1 network image saved to album (Support iOS Android)

Download the Web image and save it to the album:

1 /**
 2 * Download web image
 3 * @param uri Image Address
 4 * @returns {*}
 5 */
 6 export const DownloadImage=(uri)=> {
 7 if (!uri) return null;
 8 return new Promise((resolve, reject) => {
 9 let timestamp = (new Date()).getTime();//Get the current time error
10 let random = String(((Math.random() * 1000000) | 0))//6-bit random number
11 let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //External file, absolute path to the shared directory (android only)
12 const downloadDest = `${dirs}/${timestamp+random}.jpg`;
13 const formUrl = uri;
14 const options = {
15 fromUrl: formUrl,
16 toFile: downloadDest,
17 background: true,
18 begin: (res) => {
19 // console.log('begin', res);
20 // console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
twenty one             },
twenty two         };
23 try {
24 const ret = RNFS.downloadFile(options);
25 ret.promise.then(res => {
26 // console.log('success', res);
27 // console.log('file://' + downloadDest)
28 var promise = CameraRoll.saveToCameraRoll(downloadDest);
29 promise.then(function(result) {
30 // alert ('Save successfully! The address is as follows: \n' + result);
31 }).catch(function(error) {
32 console.log('error', error);
33 // alert ('Save failed!\n' + error);
34 });
35 resolve(res);
36 }).catch(err => {
37 reject(new Error(err))
38 });
39 } catch (e) {
40 reject(new Error(e))
41 }
42
43 })
44
45 } 


Working with instances

1 //Save the picture
  2 DownloadImage=(uri)=>{
  3 Download.DownloadImage(uri).then((res)=>{
  4 if(res.statusCode==200){
  5 Toast.show ('Image Saved Successfully')
  6 }else{
  7 Toast.show ('Image Save Failed')
  8             }
  9         })
10 .catch((error)=>{
11 Toast.show ('Image Save Failed')
12 console.log(error)
13 })
14 } 
3.2 Memory Image saved to album (Support iOS Android)


To save a memory picture to an album:

1 /**
  2 * Save image to album
  3 * @param ImageUrl Image Address
  4 * @returns {*}
  5 */
  6 export const DownloadLocalImage=(ImageUrl)=> {
  7 if (!ImageUrl) return null;
  8 return new Promise((resolve, reject) => {
  9 try {
10 var promise = CameraRoll.saveToCameraRoll(ImageUrl);
11 promise.then(function(result) {
12 resolve({statusCode:200});
13 //alert('Save successfully! The address is as follows: \n' + result);
14 }).catch(function(error) {
15 console.log('error', error);
16 // alert ('Save failed!\n' + error);
17 });
18 } catch (e) {
19 reject(new Error(e))
20 }
twenty one 
twenty two     })
twenty three 
twenty four } 




Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.