Does anyone know how to abort a download while using the $cordovaFileTransfer plugin with ionic?
I have a view where the user has the option to download a file, but I want to make sure that if they start downloading the file, but then press the "back" button, it cancels the download and basically resets the view. What seems to be happening is when the download starts and the view is left, the download still does its thing, even though I'm trying to do something like this in the code:
// If the user leaves, check if a download is in progress.
// - If so, reset the variable, and remove the directory
$scope.$on('$ionicView.leave', function() {
if($scope.downloading === true) {
$scope.downloading = false;
$cordovaFile.removeRecursively(cordova.file.dataDirectory, courseDir)
.then(function (success) {
});
}
});
I've tried calling $cordovaFileTransfer.abort() and it tells me there is no such function, even though I see an abort function in the plugin, itself. Does anyone have any insight into this, because I feel this would be a common piece of functionality that people are looking for.
Thanks!
I ended up solving this problem by going into the ng-cordova.js file directly and adding the abort function like so:
I made a global variable called ft inside of the factory object and removed the variable instantiation inside the "download" function, in order to make it global to all functions.
/* globals FileTransfer: true */
angular.module('ngCordova.plugins.fileTransfer', [])
.factory('$cordovaFileTransfer', ['$q', '$timeout', function ($q, $timeout) {
var ft = new FileTransfer();
return {
download: function (source, filePath, options, trustAllHosts) {
var q = $q.defer();
var uri = (options && options.encodeURI === false) ? source : encodeURI(source);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function () {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function (progress) {
q.notify(progress);
};
q.promise.abort = function () {
ft.abort();
};
ft.download(uri, filePath, q.resolve, q.reject, trustAllHosts, options);
return q.promise;
},
upload: function (server, filePath, options, trustAllHosts) {
var q = $q.defer();
var uri = (options && options.encodeURI === false) ? server : encodeURI(server);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function () {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function (progress) {
q.notify(progress);
};
q.promise.abort = function () {
ft.abort();
};
ft.upload(filePath, uri, q.resolve, q.reject, options, trustAllHosts);
return q.promise;
},
/* Here is the added abort function that will
kill the download or upload by calling $cordovaFileTransfer.abort() */
abort: function() {
var q = $q.defer;
ft.abort();
q.resolve;
return q.promise;
}
};
}]);