Search code examples
iosangularjscordovafilepickercordova-plugin-file

How can i read a file from iCloud in an iOS-device with cordova?


I want to read the content of a PDF file stored in iCloud.

  1. I pick the file with the FilePicker Phonegap iOS Plugin (https://github.com/jcesarmobile/FilePicker-Phonegap-iOS-Plugin). The plugin gives me the temporary path where the file is copied.

  2. I want to read it whith the Cordova File Plugin (https://github.com/apache/cordova-plugin-file) but I did something wrong and the log is always giving me an error.

Here is the code:

$scope.successCallback = function (path) {
    var fileName = path.substr(path.lastIndexOf('/') + 1);
    var fileDir = path.substr(0,path.lastIndexOf('/') + 1)
    console.log("FilePath: " + path);

    $cordovaFile.readAsDataURL(fileDir, fileName)
      .then(function (data) {
          var index = data.indexOf("base64,");
          if(index > 0)
          {
              data = data.substr(index+7);
          }
          console.log("Data OK=" + data);
      }, function (error) {
          console.log("Error reading file: " + JSON.stringify(error));
      });                 
}
window.FilePicker.pickFile($scope.successCallback, $scope.errorCallback);

And that's the output:

$FilePath: /private/var/mobile/Containers/Data/Application/22E33EF4-832B-4911-92A6-312927C42A7C/tmp/DocumentPickerIncoming/file.pdf
$Error reading file: {"code":5,"message":"ENCODING_ERR"}

What am I doing wrong?


Solution

  • I realized that in the File Path was a "tmp" folder.

    According of this, I changed the "fileDir" in order to matching the cordova.file properties map to physical paths on a real device which is referred in the iOS File System Layout of the documentation of cordova-plugin-file.

    Now it works :)

    Here is the final code:

    $scope.successCallback = function (path) {
    var fileName = path.substr(path.lastIndexOf('/') + 1);
    var fileDir = cordova.file.tempDirectory + "DocumentPickerIncoming/";
    
    console.log("FilePath: " + path);
    
    $cordovaFile.readAsDataURL(fileDir, fileName)
      .then(function (data) {
          var index = data.indexOf("base64,");
          if(index > 0)
          {
              data = data.substr(index+7);
          }
          console.log("Data OK=" + data);
          }, function (error) {
              console.log("Error reading file: " + JSON.stringify(error));
          });             
    }
    window.FilePicker.pickFile($scope.successCallback, $scope.errorCallback);