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

Gur*_*ela 2 photo-gallery imagedownload react-native

我想从 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') 
   });
Run Code Online (Sandbox Code Playgroud)

我需要iOS的权限才能将照片保存在图库中?

小智 8

对于 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 最新版本的CameraRoll有一个功能是save而不是saveToCameraRoll (2认同)
  • 谢谢你的答案。它的运行。但是,我有一个问题,当继续保存过程时,应用程序意外崩溃退出。之后,我找到了解决方案。您应该在 info.plist 中添加 NSPhotoLibraryAddUsageDescription("Privacy - 照片库添加使用说明")。这是IOS 11规则。 (2认同)