React Native Скачать изображение с URL-адреса и сохранить в галерее

Я хочу загрузить изображение с 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') 
   });

witch one Разрешения, которые мне нужны для iOS, чтобы сохранить фото в галерее?


person Gurbela    schedule 12.10.2019    source источник
comment
Похоже: stackoverflow.com/questions/46581830/   -  person Oleg    schedule 12.10.2019
comment
Я добавил NSPhotoLibraryAddUsageDescription (Privacy - Photo Library Additions Usage Description) в info.plist, но это не работает.   -  person Gurbela    schedule 12.10.2019
comment
Вы хотите сохранить в каталогах ['MainBundleDir'], почему бы не Platform.OS === 'ios'? fs.dirs.DocumentDir:   -  person Oleg    schedule 12.10.2019
comment
В iOS нет dirs.PictureDir   -  person Gurbela    schedule 12.10.2019


Ответы (2)


Вы должны использовать фотопленку.

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

  • React-native ссылка @ react-native-community / cameraroll

  • от:

    импортировать {CameraRoll} из "react-native";

    to

    импортировать CameraRoll из "@ response-native-community / cameraroll";

person Oleg    schedule 12.10.2019
comment
Не работает, как отправить запрос на разрешения? (NSPhotoLibraryAddUsageDescription) - person Gurbela; 12.10.2019
comment
Какую версию fetch blob вы используете? - person Oleg; 12.10.2019
comment
0.10.15, у меня есть react-native 0.59.9 - person Gurbela; 12.10.2019
comment
Посмотрите на stackoverflow.com/questions/54123046/ - person Oleg; 12.10.2019
comment
да, он вернулся: YellowBox.js: 67 Возможное отклонение необработанного обещания (id: 0): TypeError: Невозможно прочитать свойство saveToCameraRoll из undefined - person Gurbela; 12.10.2019
comment
npm install @ react-native-community / cameraroll --save - person Oleg; 12.10.2019
comment
React-native ссылка @ react-native-community / cameraroll - person Oleg; 12.10.2019
comment
импортировать CameraRoll из @ response-native-community / cameraroll; - person Oleg; 12.10.2019
comment
Вы должны добавить это - person Oleg; 12.10.2019

Для iOS вам не нужно использовать fetch-blob и загружать его. вам нужно использовать CameraRoll из response-native и вызвать 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);
  }
}
person Mohsin Riaz    schedule 12.10.2019
comment
В самой последней версии CameraRoll есть функция сохранения вместо saveToCameraRoll. - person Luís Mestre; 16.06.2020
comment
Спасибо за ответ. его пробег. Однако у меня есть одна проблема: при продолжении сохранения происходит неожиданный аварийный выход приложения. После этого я нашел решение. Вы должны добавить NSPhotoLibraryAddUsageDescription (Конфиденциальность - Описание использования дополнений библиотеки фотографий) в info.plist. это правило IOS 11. - person Burak Odabaş; 02.05.2021
comment
@Mohsin, как мы можем сохранять изображения на фотографии с помощью нашего альбома приложения в ios? - person Zuhair Naqi; 25.06.2021