Handling runtime permissions in Cordova

Q: I can’t load documents stored on external storage in Apache Cordova/PhoneGap/Ionic for Android.

In order 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 are not granted to your app automatically after installation. You need to explicitly ask for them before opening files via PSPDFKit.present.

You can use Android permission Cordova plugin to request these permissions in your JavaScript files.

Install the plugin first:

cordova plugin add cordova-plugin-android-permissions

You can 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, no need to request it again.
    presentDocument();
  } else {
    var error = function() {
      // Permission has been denied. This example just logs warning, 
      // make sure to handle this state in your application UI - e.g. 
      // inform your user that you can't open the PDF without their permissions 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 be now presented with the following dialog asking them to grant the required permissions:

Runtime permissions dialog

The document will now open correctly once the external storage permission has been granted.