Handling runtime permissions in Cordova
To read and write files on the external storage, your app must acquire READ_EXTERNAL_STORAGE
and WRITE_EXTERNAL_STORAGE
permissions. To acquire these permissions, add them to your manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.app.package"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
If your app targets Android 6.0+, these permissions aren’t granted to your app automatically after installation. Instead, you need to explicitly ask for them before opening files via PSPDFKit.present
.
You can use the Android Permission Cordova Plugin to request these permissions in your JavaScript files.
Install the plugin first:
cordova plugin add cordova-plugin-android-permissions
Then handle the permissions request before presenting the document:
function presentDocument() { PSPDFKit.present(documentUri); } var permissions = cordova.plugins.permissions; permissions.hasPermission( permissions.READ_EXTERNAL_STORAGE, function (status) { if (status.hasPermission) { // Permission has been granted previously, so there is no need to request it again. presentDocument(); } else { var error = function () { // Permission has been denied. This example just logs a warning, so // make sure to handle this state in your application UI — e.g. // inform your user that you can't open the PDF without their permission, or similar. console.warn('External storage permission has been denied'); }; var success = function (status) { if (!status.hasPermission) { // Permission has been denied. error(); } else { // Permission has been granted. Present the document. presentDocument(); } }; // Request the permission to read files from external storage. permissions.requestPermission( permissions.READ_EXTERNAL_STORAGE, success, error, ); } }, );
Your users will now be presented with the following dialog asking them to grant the required permissions.
Once the external storage permission has been granted, the document will open correctly.