platform.ready() method is not firing in Android device using ionic - android

I am Developing an Ionic Application that Upload, downloads, and delete attachments
Here I use the File Plugin inside the platform. ready() and build APK. when I run the APK on an android device the code inside the Platform.ready is not getting fired what is the problem???
import { Platform } from '#ionic/angular';
import { File } from '#ionic-native/file/ngx';
constructor(private cFile: File,private platform: Platform){}
DownloadAttachment()
{
var buffer = pFilebytearray.replace(/\"/g, "");
var byteCharacters = atob(buffer);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
this.cFile.dataDirectory
var byteArray = new Uint8Array(byteNumbers);
let aType: any = "";
let aMimeTypeJson = {} as any;
aMimeTypeJson = this.GetMimeType(pAttachmentType.toLowerCase())
aType = aMimeTypeJson.MimeType;
var blob1 = new Blob([byteArray], { type: aType });
alert("completed the Name Seperation and Blob Creation")
this.platform.ready().then(() => {
alert("Download Starts...");
let result = this.cFile.createDir(this.cFile.externalDataDirectory, "Documents", true).then(data => {
let dirpath = data.toURL();
alert("Dir created at" + dirpath);
this.cFile.writeFile(dirpath, pAttachmentName, blob1, { replace: true })
.then((Result) => {
this.MessageDialog("Message", "Attachment downloaded " + dirpath, false, true);
}, (error) => {
this.MessageDialog("Message", "Attachment not downloaded", false, true);
});
}).catch(error => {
alert("error" + error);
});
})
}

The Error Solved for me after using Async, await. This makes the code wait till the platform gets ready
async AttachmentDownload(pFilebytearray, pAttachmentType, pAttachmentName): Promise<void> {
alert("entering AttachmentDownload")
var buffer = pFilebytearray.replace(/\"/g, "");
var byteCharacters = atob(buffer);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
this.cFile.dataDirectory
var byteArray = new Uint8Array(byteNumbers);
let aType: any = "";
let aMimeTypeJson = {} as any;
aMimeTypeJson = this.GetMimeType(pAttachmentType.toLowerCase())
aType = aMimeTypeJson.MimeType;
var blob1 = new Blob([byteArray], { type: aType });
alert("completed the Name Seperation and Blob Creation")
await this.platform.ready().then(() => {
alert("Download Starts...");
let result = this.cFile.createDir(this.cFile.externalDataDirectory, "Documents", true).then(data => {
let dirpath = data.toURL();
alert("Dir created at" + dirpath);
this.cFile.writeFile(dirpath, pAttachmentName, blob1, { replace: true })
.then((Result) => {
this.MessageDialog("Message", "Attachment downloaded " + dirpath, false, true);
}, (error) => {
this.MessageDialog("Message", "Attachment not downloaded", false, true);
});
}).catch(error => {
alert("error" + error);
});
})
}

Related

WEBPACK_IMPORTED_MODULE_1__ionic_native_file__.FileReader is not a constructor

I have this snippet that I have been trying to upload an image with to Firebase server. I throws an error. How do I solve this?
cordova.js:311 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_1__ionic_native_file__.FileReader is not a constructor
at main.js:404
at win (FileEntry.js:85)
at Object.callbackFromNative (cordova.js:291)
at <anonymous>:1:9
code snippet:
uploadimage() {
var promise = new Promise((resolve, reject)=> {
this.filechooser.open().then((url)=> {
(<any>window).FilePath.resolveNativePath(url, (result)=> {
console.log("This is the url: ---- :" +url +" " +" This is the result " +result);
this.nativepath = result;
(<any>window).resolveLocalFileSystemURL(this.nativepath, (res)=> {
res.file((resFile)=> {
var reader = new FileReader();
reader.readAsArrayBuffer(resFile);
reader.onloadend = (ent: any) => {
var imgBlob = new Blob([ent.target.result], { type: 'image/jpeg'});
var imgStore = this.firestore.ref('/profileimages').child(firebase.auth().currentUser.uid);
imgStore.put(imgBlob).then((res)=> {
this.firestore.ref('/profileimages').child(firebase.auth().currentUser.uid).getDownloadURL().then((url)=> {
resolve(url);
}).catch((error)=> {
reject(error);
})
}).catch((error)=> {
alert('Upload failed' + error);
})
}
})
})
})
})
})
return promise;
}

Unable to retrieve access token for Moodle on Android phone

I have created an authentication service based on Jason Watmore's example, and it works fine in the Ripple emulator for Android, logs in, saves the token to jStorage, and uses it to access other web services.
It was also working in the actual Android phone till yesterday.
I have tested to see if jStorage is working in my Android phone (it is), and I have tried removing all the app's data using the Settings.
Any idea why the Android phone is not fetching the token from the Moodle server (but the emulator is fetching it)?
Here's my service:
myApp.factory('AuthenticationService',
['$http', '$cookies', '$rootScope', '$timeout', '$log',
function ($http, $cookies, $rootScope, $timeout, $log) {
var service = {};
service.Login = function (username, password, callback) {
//$log.info('Login function called');
if ((username.length && password.length) && (username !== '' && password != '')) {
var loginUrl = 'https://my.moodle.url/local/token.php';
// use $.param jQuery function to serialize data from JSON
var data = $.param({
username: username,
password: password,
service: 'brookesid_ws'
});
//$log.info(data);
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(loginUrl, data, config)
.success(function (data, status, headers, config) {
$log.info(data);
myToken = data.token;
dataString = JSON.stringify(data);
if (dataString.indexOf('error') > 0) {
$rootScope.className = 'error';
$rootScope.PostDataResponse = 'Invalid user credentials, please try again';
$rootScope.isAuthenticated = false;
$rootScope.dataLoading = false;
}
else {
$.jStorage.set('session', myToken, { TTL: 28800000 });
//$cookies.put('session', myToken);
}
$rootScope.isAuthenticated = true;
// $log.info('isAuthenticated = true');
callback(dataString);
})
.error(function (data, status, header, config) {
$rootScope.isAuthenticated = false;
$rootScope.ResponseDetails = "data: " + data +
"<br />status: " + status +
"<br />headers: " + header +
"<br />config: " + config;
responsedata = JSON.stringify(data);
callback(responsedata);
$log.info('error: '+responsedata);
});
} else {
$rootScope.className = 'error';
$rootScope.isAuthenticated = false;
$rootScope.PostDataResponse = 'Please enter a username and password';
}
};
service.SetCredentials = function (sessionToken) {
var JSONObject = JSON.parse(sessionToken);
var key = 'token';
myToken = JSONObject[key];
$log.info('session Token: ' + sessionToken);
$log.info('myToken: ' + myToken);
$rootScope.globals = {
currentUser: {
token: myToken
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + sessionToken; // jshint ignore:line
//retrieve last login date and then update it
$rootScope.lastLogin = $.jStorage.get('lastLogin', '');
var today = new Date();
epochToday = Math.round(today.getTime() / 1000);
$.jStorage.set('lastLogin', epochToday, { TTL: 28800000 });
//$log.info('Rootscope Last Login: '+$rootScope.lastLogin);
$.jStorage.set('globals', $rootScope.globals, { TTL: 28800000 });
$.jStorage.set('session', myToken, { TTL: 28800000 });
$.jStorage.set('loginStatus', 'logged in', { TTL: 28800000 });
$log.info('Token (jStorage) ' + $.jStorage.get('session', ''));
//$log.info('Last login (jStorage) ' + $.jStorage.get('lastLogin', ''));
//$log.info('Login status (jStorage) ' + $.jStorage.get('loginStatus', ''));
};
service.ClearCredentials = function () {
$rootScope.globals = {};
//$cookies.remove('globals');
//$cookies.remove('session');
$.jStorage.deleteKey('globals');
$.jStorage.deleteKey('session');
$http.defaults.headers.common.Authorization = 'Basic ';
};
return service;
}])
Here is my login Controller:
.controller('loginCtrl',
['$scope', '$rootScope', '$location', 'AuthenticationService', '$routeParams', '$http',
function ($scope, $rootScope, $location, AuthenticationService, $routeParams, $http) {
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function (response) {
responsedata = JSON.stringify(response);
/* error handling*/
if (responsedata.indexOf('error') > 0 || responsedata.indexOf('invalid') > 0) {
$scope.error = response.message;
$rootScope.className = 'error';
$rootScope.dataLoading = false;
} else {
AuthenticationService.SetCredentials(response);
console.log('response: '+response);
$location.path('/home');
};
});
};
$scope.logout = function () {
$rootScope.dataLoading = false;
$rootScope.hideMe = true;
$rootScope.PostDataResponse = '';
$rootScope.ResponseDetails = '';
//alert('logging out');
AuthenticationService.ClearCredentials();
};
$scope.showMenuPanel = function () {
$scope.hideMenuPanel = false;
};
$scope.doHideMenuPanel = function () {
$scope.hideMenuPanel = true;
$rootScope.PostDataResponse = '';
};
}])
It was actually the Cordova app's URL whitelisting settings that were causing the problem.

Browsers crash when using URL.createObjectURL

Using android, browsers (FF, Chrome, ...) crash when i use this instruction :
img.src = blob;
Any idea ?
the complete source :
$("#file-input").on("change", function (e) {
if (window.URL) {
var img = document.createElement("img");
img.onload = function (e) {
img.width = 100;
document.getElementById("preview").appendChild(img);
URL.revokeObjectURL(img.src);
parent.window.$.mobile.loading("show");
window.setTimeout(function () {
startUploading();
}, 2500);
};
var blob = URL.createObjectURL(e.target.files[0]);
img.src = blob;
}
else {
// fallback to FileReader for FF3.6
reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
document.getElementById('preview').innerHTML = ['<img src="', e.target.result, '" width="100" />'].join('');
parent.window.$.mobile.loading("show");
window.setTimeout(function () {
startUploading();
}, 2500);
};
})(f);
reader.readAsDataURL(e.target.files[0]);
}
});
thanks in advance.

Phonegap "Error calling method on NPObject" while uploading the image from android device

I am new to phonegap and i am having the issue when uploading the image from android device, the I think the window.resolveLocalFileSystemURI function throws an Error calling method on NPObject error, my complete code is as below. Please have a look and share your ideas.
navigator.camera.getPicture(function (imageURI) {
var _this = this;
var encodedURL = encodeURI("http://api.xyz.com/DataService/DataService.svc/UploadImage");
try {
this.op = new FileUploadOptions();
this.op.fileKey = "file";
this.op.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
this.op.mimeType = "image/jpeg";
this.op.chunkedMode = false;
this.op.headers = { Connection: "close" };
this.ft = new FileTransfer();
if (window.device != undefined && device.platform == "Android") {
window.resolveLocalFileSystemURI(imageURI, function (fileEntry) {
fileEntry.file(function (fileObj) {
var fileFullPath = fileObj.fullPath;
_this.op.fileName = fileFullPath.substr(fileFullPath.lastIndexOf('/') + 1);
_this.ft.upload(fileFullPath, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, _this.op, true);
});
});
} else {
this.ft.upload(imageURI, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, this.op, true);
}
} catch (_error) {
alert(_error);
}
},
function (message) { },
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}

Can't upload photo from Storage Access Framework on Android 4.4 using phonegap

I have this code for uploading photo on server
photo: function () {
var self = this;
navigator.camera.getPicture(function
getPhotoTicket(function (ticket) {
var options = new FileUploadOptions();
var fileName = {};
options.fileKey = "upload_file";
try {
window.resolveLocalFileSystemURI(imageURI, onSuccess, onError);
} catch (e) {
console.log(e.toString());
fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1)+'.jpg';
}
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "keep-alive"
};
options.httpMethod = "POST";
var params = {};
params.upload_ticket = ticket;
options.params = params;
function reload() {
getProfile(userID, function () {
app.profile_editor();
}, true);
}
function onSuccess(fileEntry) {
fileName = fileEntry.name;
}
function onError(fileEntry) {
fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1) + '.jpg';
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(URL + "api/index/fileupload"), function (success) {
alert('PHOTO UPDATED');
reload();
}, function (error) {
alert('error');
}, options);
});
}, function () {
console.log("error getting image")
}, {
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: navigator.camera.DestinationType.FILE_URI
});
}
it works fine on Android 4.3 and lower. But on Android KitKat i get imageURI like:
content://com.android.providers.media.documents/document/image%3A352
In this post Unable to load image when selected from the gallery on Android 4.4 (KitKat) using PhoneGap Camera Plugin
MBillau suggest to set the destination type to DATA_URL. I tried but had no success. Could someone suggest how I need to refactor my code?

Categories

Resources