From b84d530fc682af105fbb0fc58abfb6fb7bff52e5 Mon Sep 17 00:00:00 2001 From: --local <--local> Date: Thu, 23 Feb 2023 17:45:15 +0600 Subject: [PATCH] docs: resolve permission issue for android --- example/app.json | 17 +++++++++++---- example/src/examples/DownloadQR.tsx | 34 +++++++++++++++++++++-------- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/example/app.json b/example/app.json index 3d6068f..5e398e5 100644 --- a/example/app.json +++ b/example/app.json @@ -5,11 +5,11 @@ "version": "1.0.0", "orientation": "portrait", "icon": "./assets/icon.png", - "userInterfaceStyle": "light", + "userInterfaceStyle": "dark", "splash": { "image": "./assets/splash.png", "resizeMode": "contain", - "backgroundColor": "#ffffff" + "backgroundColor": "#222" }, "updates": { "fallbackToCacheTimeout": 0 @@ -23,11 +23,20 @@ "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", - "backgroundColor": "#FFFFFF" + "backgroundColor": "#222" } }, "web": { "favicon": "./assets/favicon.png" - } + }, + "plugins": [ + [ + "expo-media-library", + { + "savePhotosPermission": "Allow $(PRODUCT_NAME) to save photos.", + "isAccessMediaLocationEnabled": true + } + ] + ] } } diff --git a/example/src/examples/DownloadQR.tsx b/example/src/examples/DownloadQR.tsx index 66af17b..9d4022b 100644 --- a/example/src/examples/DownloadQR.tsx +++ b/example/src/examples/DownloadQR.tsx @@ -5,21 +5,37 @@ import QRCodeStyled from 'react-native-qrcode-styled'; import * as FileSystem from 'expo-file-system'; import * as MediaLibrary from 'expo-media-library'; +// also need to add MEDIA_LIBRARY permission for android +// https://docs.expo.dev/versions/latest/sdk/media-library/#configuration-in-appjsonappconfigjs export default function DownloadQR() { + const [permissionResponse, requestPermission] = MediaLibrary.usePermissions(); const QRRef = useRef(null); - const handlePressDownload = () => { - QRRef.current?.toDataURL(async (base64Code: string) => { - const filename = FileSystem.documentDirectory + 'qr_code.png'; + const handlePressDownload = async () => { + try { + let isPermissionGranted = permissionResponse?.granted; + if (!isPermissionGranted) { + isPermissionGranted = (await requestPermission()).granted; + } - await FileSystem.writeAsStringAsync(filename, base64Code, { - encoding: FileSystem.EncodingType.Base64, - }); + if (!isPermissionGranted) { + throw new Error('Library permission access denied'); + } + + QRRef.current?.toDataURL(async (base64Code: string) => { + const filename = FileSystem.documentDirectory + 'qr_code.png'; - await MediaLibrary.saveToLibraryAsync(filename); - Alert.alert('QR downloaded!'); - }); + await FileSystem.writeAsStringAsync(filename, base64Code, { + encoding: FileSystem.EncodingType.Base64, + }); + + await MediaLibrary.saveToLibraryAsync(filename); + Alert.alert('QR downloaded!'); + }); + } catch (error) { + console.error('QR downloading failed: ', error); + } }; return (