Last active
December 27, 2020 05:06
-
-
Save tinacious/5e4d752f951d452360aa58c52145b380 to your computer and use it in GitHub Desktop.
Verify Android read/write permissions in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PermissionsAndroid } from 'react-native'; | |
import DeviceInfo from 'react-native-device-info'; | |
/** | |
* Depending on the version of Android, we need to check different permissions | |
* to enable this functionality. | |
* Android Q and above only require read permission. | |
* Older versions require both read and write. | |
* | |
* Also make sure you have the following permissions in your manifest. | |
* | |
* <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> | |
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" | |
* android:maxSdkVersion="28" /> | |
*/ | |
export async function hasStoragePermissions() { | |
const systemVersion = DeviceInfo.getSystemVersion(); | |
const androidVersion = Number(systemVersion.split('.')[0]); | |
const readPermission = PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE; | |
const writePermission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE; | |
if (androidVersion < 10) { | |
// Legacy Android | |
const hasWritePermission = await PermissionsAndroid.check(writePermission); | |
if (hasWritePermission) { | |
return true; | |
} | |
const writeStatus = await PermissionsAndroid.request(writePermission); | |
return writeStatus === 'granted'; | |
} else { | |
// Android Q+ | |
const hasReadPermission = await PermissionsAndroid.check(readPermission); | |
if (hasReadPermission) { | |
return true; | |
} | |
const readStatus = await PermissionsAndroid.request(readPermission); | |
return readStatus === 'granted'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment