美文网首页ReactNativeReact Native开发技巧React Native实践
ReactNative图片保存到相册(Android 和 ios

ReactNative图片保存到相册(Android 和 ios

作者: 呼呼哥 | 来源:发表于2018-06-27 11:28 被阅读68次

ios 保存:

React Native 的 CameraRoll API 提供了访问本地相册的功能(经过测试该组件只支持 ios)

第一步

如果该库包含原生代码,那么在它的文件夹下一定有一个.xcodeproj文件。 把这个文件拖到你的XCode工程下(通常拖到XCode的Libraries分组里)

image.png

第二步

点击你的主工程文件,选择Build Phases,然后把刚才所添加进去的.xcodeproj下的Products文件夹中的静态库文件(.a文件),拖到Link Binary With Libraries组内。

image.png
第三步:
然后添加库所在的目录(如果它还有像React这样的子目录需要包含,注意要选中recursive选项)
image.png

代码使用:

import {Platform,CameraRoll} from 'react-native';
 var promise = CameraRoll.saveToCameraRoll("图片的 url")
            promise.then(function(result) {
                this.refs.toast.show("图片已保存至相册")
            }).catch(function(error) {
                this.refs.toast.show("保存失败")
            })
Android 保存:
Android 的保存使用CameraRoll配合 react-native-fs 进行实现保存图片

具体实现代码:

const RNFS = require('react-native-fs'); //文件处理
const storeLocation = `${RNFS.DocumentDirectoryPath}`;
     let pathName = new Date().getTime() + "文件名.png"
     let downloadDest = `${storeLocation}/${pathName}`;
      const ret = RNFS.downloadFile({fromUrl:saveImageUrl,toFile:downloadDest});
      ret.promise.then(res => {
        if(res && res.statusCode === 200){
            var promise = CameraRoll.saveToCameraRoll("file://" + downloadDest);
            promise.then(function(result) {
               console.log("图片已保存至相册")
            }).catch(function(error) {
               console.log("保存失败")
            })
        }
      })

ok 大功告成

相关文章

网友评论

  • uuuuuuw:原来这样也可以实现 就是不知道在 android高版本下 有没有影响
    呼呼哥:@林唷嘉 应该没有问题,fs就是文件储存

本文标题:ReactNative图片保存到相册(Android 和 ios

本文链接:https://www.haomeiwen.com/subject/aklbyftx.html