This commit is contained in:
tx 2024-12-26 14:30:42 +08:00
parent 05872f47d7
commit e184055bee

View File

@ -5,13 +5,13 @@ import { RouteProp, useRoute } from '@react-navigation/native';
import RNFS from 'react-native-fs';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { Spinner, Layout } from '@ui-kitten/components';
import QRCode from 'react-native-qrcode-svg'; // 新增的库
const ShareQrcode = () => {
const route = useRoute<RouteProp<RootStackParamList, 'ShareQrcode'>>();
const { QrId } = route.params;
const [loading, setLoading] = useState(true);
const [qrCodeRef, setQrCodeRef] = useState(null); // 用于保存二维码的引用
const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${rpx(400)}x${rpx(400)}&data=https://testlu.chuangtewl.com/prod-api?keyId=${QrId}`;
useEffect(() => {
const timer = setTimeout(() => {
@ -20,70 +20,64 @@ const ShareQrcode = () => {
return () => clearTimeout(timer);
}, []);
const saveToGallery = async () => {
try {
// 检查并请求权限
let permissionResult;
if (Platform.OS === 'android') {
if (Platform.Version >= 33) {
permissionResult = await request(PERMISSIONS.ANDROID.READ_MEDIA_IMAGES);
} else {
permissionResult = await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
}
}
const writePermission = await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
const readPermission = await request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE);
if (permissionResult === RESULTS.GRANTED || Platform.OS === 'ios') {
qrCodeRef.toDataURL(async (data) => {
try {
// 使用 ExternalDirectoryPath这个目录在大多数 Android 设备上都可以访问
const basePath = Platform.OS === 'android'
? `${RNFS.ExternalDirectoryPath}`
: RNFS.DocumentDirectoryPath;
const fileName = `qrcode_${Date.now()}.png`;
const filePath = `${basePath}/${fileName}`;
if (writePermission === RESULTS.GRANTED && readPermission === RESULTS.GRANTED) {
try {
let directoryPath = `${RNFS.DownloadDirectoryPath}`;
const fileName = `qrcode_${Date.now()}.jpg`;
let downloadDest = `${directoryPath}/${fileName}`;
// 直接写入文件
await RNFS.writeFile(filePath, data, 'base64');
if (Platform.OS === 'android') {
// 使用 CameraRoll 保存到相册
const { CameraRoll } = NativeModules;
if (CameraRoll && CameraRoll.saveToCameraRoll) {
await CameraRoll.saveToCameraRoll(`file://${filePath}`, 'photo');
// 删除临时文件
await RNFS.unlink(filePath);
Alert.alert('成功', '二维码已保存到相册');
} else {
// 如果 CameraRoll 模块不可用,尝试使用 MediaScanner
NativeModules.MediaScanner.scanFile(filePath, 'image/png', (err) => {
if (err) {
console.error('媒体扫描错误:', err);
Alert.alert('提示', '二维码已保存,但可能需要手动刷新相册');
} else {
Alert.alert('成功', '二维码已保存到相册');
}
});
}
} else {
// iOS 处理
Alert.alert('成功', '二维码已保存');
// 检查目录是否存在
let exists = await RNFS.exists(directoryPath);
if (!exists) {
try {
await RNFS.mkdir(directoryPath);
} catch (mkdirError) {
// 使用备用路径
directoryPath = `${RNFS.ExternalStorageDirectoryPath}`;
downloadDest = `${directoryPath}/${fileName}`;
}
} catch (err) {
console.error('文件操作错误:', err);
Alert.alert('错误', '保存失败,请检查存储权限');
}
});
// 下载文件
const options = {
fromUrl: qrCodeUrl,
toFile: downloadDest,
};
const response = await RNFS.downloadFile(options).promise;
if (response.statusCode === 200) {
const fileExists = await RNFS.exists(downloadDest);
if (fileExists) {
// 刷新媒体库
NativeModules.MediaScanner.scanFile(downloadDest, 'image/jpeg', (err) => {
if (err) {
Alert.alert('错误', '无法刷新媒体库');
} else {
Alert.alert('成功', '二维码已保存到相册');
}
});
} else {
throw new Error('文件未能成功创建');
}
} else {
Alert.alert('错误', '下载失败,请检查网络连接');
}
} catch (err) {
Alert.alert('错误', '保存失败,无法访问存储空间');
}
} else {
Alert.alert('提示', '需要存储权限才能保存二维码,请在设置中授予权限');
Alert.alert('权限不足', '请在设置中授予存储权限');
}
} catch (error) {
console.error('保存过程错误:', error);
Alert.alert('错误', '保存失败,请重试');
}
};
if (loading) {
return (
<Layout style={styles.loadingContainer}>
@ -104,13 +98,9 @@ const ShareQrcode = () => {
style={styles.qrBack}
>
<Layout style={styles.qrContainer}>
<QRCode
value={`https://testlu.chuangtewl.com/prod-api?keyId=${QrId}`}
size={rpx(438)}
getRef={(c) => setQrCodeRef(c)} // 保存二维码的引用
logo={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u3giTY4VkWYpnGWRuFHF' }} // 添加 logo
logoSize={rpx(100)} // 设置 logo 大小
logoBackgroundColor='transparent' // 设置 logo 背景透明
<Image
source={{ uri: qrCodeUrl }}
style={styles.qrCode}
/>
</Layout>
</ImageBackground>