React Native从url下载图像并保存在Gallery中

时间:2019-10-12 15:10:31

标签: react-native photo-gallery imagedownload

我要从URL下载图像并保存在图库中。

此来源在Android上效果很好,但在iOS上效果不佳。

import RNFetchBlob from "rn-fetch-blob";


let imgUrl = 'https://static.scientificamerican.com/sciam/cache/file/EAF12335-B807-4021-9AC95BBA8BEE7C8D_source.jpg'

let newImgUri = imgUrl.lastIndexOf('/');
let imageName = imgUrl.substring(newImgUri);

let dirs = RNFetchBlob.fs.dirs;
let path = Platform.OS === 'ios' ? dirs['MainBundleDir'] + imageName : dirs.PictureDir + imageName;

 RNFetchBlob.config({
     fileCache: true,
     appendExt: 'png',
     indicator: true,
     IOSBackgroundTask: true,
     path: path,
     addAndroidDownloads: {
         useDownloadManager: true,
         notification: true,
         path: path,
         description: 'Image'
      },

     }).fetch("GET", imgUrl).then(res => { 
            console.log(res, 'end downloaded') 
   });

在iOS上需要我一个权限,才能将照片保存在图库中?

2 个答案:

答案 0 :(得分:1)

您必须使用相机胶卷。

  • npm install @ react-native-community / cameraroll --save

  • 反应本地链接@ react-native-community / cameraroll

  • 来自:

    从“ react-native”导入{CameraRoll};

    从“ @ react-native-community / cameraroll”导入CameraRoll;

答案 1 :(得分:0)

对于iOS,您无需使用fetch-blob进行下载。 您需要从react-native使用CameraRoll并调用saveToCameraRoll()

https://facebook.github.io/react-native/docs/cameraroll

import RNFetchBlob from "rn-fetch-blob";
import { CameraRoll, Platform } from "react-native";

let imgUrl = 'https://static.scientificamerican.com/sciam/cache/file/EAF12335-B807-4021-9AC95BBA8BEE7C8D_source.jpg'

let newImgUri = imgUrl.lastIndexOf('/');
let imageName = imgUrl.substring(newImgUri);

let dirs = RNFetchBlob.fs.dirs;
let path = Platform.OS === 'ios' ? dirs['MainBundleDir'] + imageName : dirs.PictureDir + imageName;

saveToGallery = () => {
  if (Platform.OS == 'android') {

    RNFetchBlob.config({
      fileCache: true,
      appendExt: 'png',
      indicator: true,
      IOSBackgroundTask: true,
      path: path,
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path: path,
        description: 'Image'
      },

    }).fetch("GET", imgUrl).then(res => {
      console.log(res, 'end downloaded')
    });
  } else {
    CameraRoll.saveToCameraRoll(imgUrl);
  }
}