IOS配置CameraRoll API
-
用Xcode打開項目, 找到
Libraries
目錄梨树,右鍵選擇Add Files to [your project's name]
-
在
{project}/node_modules/react-native/Libraries/CameraRoll
中找到RCTCameraRoll.xcodeproj
文件漆腌,并添加
-
在XCode中選擇你的項目横缔, 選擇
General
并將RCTCameraRoll.xcodeproj
下的Products
文件夾中的靜態(tài)庫文件.a
文件添加到Link Binary With Libraries
中,拖過去即可
-
配置訪問相冊的權(quán)限,打開
Info.plist
蝙昙,添加Privacy - Photo Library Additions Usage Description
和Privacy - Photo Library Usage Description
Android可以直接訪問CameraRoll API
import { Platform, CameraRoll } from 'react-native';
import RNFS from 'react-native-fs';
應(yīng)用
網(wǎng)絡(luò)圖片保存到相冊
/**
* 下載網(wǎng)頁圖片
* @param uri 圖片地址
* @returns {*}
*/
export const DownloadImage=(uri)=> {
if (!uri) return null;
return new Promise((resolve, reject) => {
let timestamp = (new Date()).getTime();//獲取當前時間錯
let random = String(((Math.random() * 1000000) | 0))//六位隨機數(shù)
let dirs = Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; //外部文件轻局,共享目錄的絕對路徑(僅限android)
const downloadDest = `${dirs}/${timestamp+random}.jpg`;
const formUrl = uri;
const options = {
fromUrl: formUrl,
toFile: downloadDest,
background: true,
begin: (res) => {
// console.log('begin', res);
// console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
},
};
try {
const ret = RNFS.downloadFile(options);
ret.promise.then(res => {
// console.log('success', res);
// console.log('file://' + downloadDest)
var promise = CameraRoll.saveToCameraRoll(downloadDest);
promise.then(function(result) {
// alert('保存成功!地址如下:\n' + result);
}).catch(function(error) {
console.log('error', error);
// alert('保存失數惨恪蒜撮!\n' + error);
});
resolve(res);
}).catch(err => {
reject(new Error(err))
});
} catch (e) {
reject(new Error(e))
}
})
}
- 使用實例
//保存圖片
DownloadImage=(uri)=>{
Download.DownloadImage(uri).then((res)=>{
if(res.statusCode==200){
Toast.show('圖片保存成功')
}else{
Toast.show('圖片保存失敗')
}
}).catch((error)=>{
Toast.show('圖片保存失敗')
console.log(error)
})
}
內(nèi)存圖片保存到相冊
/**
* 保存圖片到相冊
* @param ImageUrl 圖片地址
* @returns {*}
*/
export const DownloadLocalImage=(ImageUrl)=> {
if (!ImageUrl) return null;
return new Promise((resolve, reject) => {
try {
var promise = CameraRoll.saveToCameraRoll(ImageUrl);
promise.then(function(result) {
resolve({statusCode:200});
//alert('保存成功!地址如下:\n' + result);
}).catch(function(error) {
console.log('error', error);
// alert('保存失斂妒取淀弹!\n' + error);
});
} catch (e) {
reject(new Error(e))
}
})
}