ReactNative 保存图片到相册(使用pod管理)
2018-12-27 本文已影响21人
JamesSawyer
如果没有使用pod 管理iOS端的库,可以直接看这一篇文章:
如果你使用pod管理项目,则需要将 RCTCameraRoll
添加到pod file中,具体:
# podfile
source 'https://github.com/CocoaPods/Specs.git'
# Required for Swift apps
platform :ios, '8.0'
use_frameworks!
# The target name is most likely the name of your project.
target 'swift-2048' do
# Your 'node_modules' directory is probably in the root of your project,
# but if not, adjust the `:path` accordingly
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'CxxBridge', # Include this for RN >= 0.47
'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
'RCTText',
'RCTNetwork',
'RCTWebSocket', # needed for debugging
# Add any other subspecs you want to use in your project
'RCTCameraRoll', # !!! 将相册添加到这里 ---- 看这一行 ----
]
# Explicitly include Yoga if you are using RN >= 0.42.0
pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
# Third party deps podspec link
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end
添加到podfile中后,使用 pod install
进行安装。
安装完成之后, 需要在 Info.plist
文件中添加权限,注意iOS11+ 和 iOS10 2个权限都不一样,因此需要把2个权限都添加进去,如果不添加权限,应用会闪退:
在Info.plist中添加:
# ios11
Privacy - Photo Library Additions Usage Description String 应用需要访问您的相册(这个可自定义)
# ios10
Privacy - Photo Library Usage Description String 应用需要访问您的相册(这个可自定义)
做完上面操作后,**千万记住将项目clean一下,否则可能报 RCTCameraRollManager is undefined
错误!!! **
clean完之后即可使用 CameraRoll
import { CameraRoll } from 'react-native';
class Demo extends Component {
// ...
saveImageToCameraRoll() {
CameraRoll.save(imgURL, 'photo')
// 这一步的时候iOS会弹出提示 '应用需要访问您的相册'
// 即上面Info.plist中定义的权限文字
.then((imgPathToSave) => {
// 成功保存 imgPathToSave 将显示文件保存的路径
// eg: 'assets-library://asset/....'
})
.catch(err => {
// 保存失败
})
}
}
上面仅仅介绍了iOS端的使用方式,android端的可以参考:
另外 CameraRoll
官方文档: