Phonegap + Photoswipe with remote images - android

I have been struggling with Phonegap and Photoswipe. Here is what I have:
1) Currently I am requesting remote images via a php JSON call (working)
2) JSON images are returned and store locally to the Android device(working)
3) All images show up on Photswipe thumbnail gallery page (working)
problem is here
4) when I click on a thumbnail image, I'm not getting the Photoswipe gallery format, it just loads an the image to a blank page.
My guess is the photoswipe script is loading before I have completely passed all the images to the <#gallery
My question is how to re-initialize Photoswipe to read all the images or how to attached the Photoswipe function to the images that are appended to the
I'm trying to post the code I have working now, having trouble with the formatting here.
//Global instance of DirectoryEntry for our data
var DATADIR;
var knownfiles = [];
//Loaded my file system, now let's get a directory entry for where I'll store my crap
function onFSSuccess(fileSystem) {
fileSystem.root.getDirectory("Android/data/com.moto.photoloader",create:true,exclusive:false},gotDir,onError);
}
//The directory entry callback
function gotDir(d){
console.log("got dir");
DATADIR = d;
var reader = DATADIR.createReader();
reader.readEntries(function(d){
gotFiles(d);
appReady();
},onError);
}
//Result of reading my directory
function gotFiles(entries) {
console.log("The dir has "+entries.length+" entries.");
for (var i=0; i<entries.length; i++) {
console.log(entries[i].name+' dir? '+entries[i].isDirectory);
knownfiles.push(entries[i].name);
renderPicture(entries[i].fullPath);
}
}
function renderPicture(path){
$("#Gallery").append("<li><a href='"http://myurltofullimages"'><img src='"+path+"' alt=\"Image 018\"/></a></li>");
console.log("<li><a href='"/myurltofullimages"'><img src='"+path+"' alt=\"Image 018\"/></a></li>");
}
function onError(e){
console.log("ERROR");
console.log(JSON.stringify(e));
}
function onDeviceReady() {
//what do we have in cache already?
$("#status").html("Checking your local cache....");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, null);
}
function appReady(){
$("#status").html("Ready to check remote files...");
$.get("http://myurltojsonphp/photo_upload/json.php", {}, function(res) {
if (res.length > 0) {
$("#status").html("Going to sync some images...");
for (var i = 0; i < res.length; i++) {
if (knownfiles.indexOf(res[i]) == -1) {
console.log("need to download " + res[i]);
var ft = new FileTransfer();
var dlPath = DATADIR.fullPath + "/" + res[i];
console.log("downloading crap to " + dlPath);
ft.download("http://myurl/photo_upload/am/woman/thumb/" + escape(res[i]), dlPath, function(){
renderPicture(e.fullPath);
console.log("Successful download of "+e.fullPath);
}, onError);
}
}
}
$("#status").html("");
}, "json");
}
{
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
<script type="text/javascript">
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function(){
var
options = {},
instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
}, false);
}(window, window.Code.PhotoSwipe));
</script>

After receiving the photos by the GET call, you must initialize photoswipe gallery:
$("ul.gallery a").photoSwipe(
{
allowUserZoom: false,
jQueryMobile: true,
autoStartSlideshow: false,
backButtonHideEnabled: false,
captionAndToolbarAutoHideDelay: 0,
preventSlideshow: true
});

Related

How to download base-64 source images in mobile device(Android,iPhone,Windows) and save into device phone memory

I have created one sample app using telerik app builder. I have created one simple view and one js file, render one image in view and convert it into base-64. I have requirement to download this image and save it to device internal storage using javascript
I have used download.js plugin of javascript but download functionality is not working.Please give suggestion.
My Code is below:
function (image)
{
var imageData = image.src;
imageData = imageData.replace('data:image/png;base64,', '');
download(imageData, "image11111", "image/png");
}
I found my own question's answer.
You can download image in mobile device using cordova filetransfer.
function download()
{
var filepath = encodeURI("http://www.telerik.com/sfimages/default-source/logos/app_builder.png"),
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile("sample.jpg", { create: true, exclusive: false }, function (fileEntry) {
// get the full path to the newly created file on the device
var localPath = fileEntry.fullPath;
// massage the path for android devices (not tested)
if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
localPath = localPath.substring(7);
}
// download the remote file and save it
var remoteFile = filepath;
//loadingOverlay.displayLoading("Image will be save on your device.");
var fileTransfer = new FileTransfer();
fileTransfer.download(remoteFile, localPath, function (newFileEntry) {
// successful download, continue to the next image
var dwnldImagePath = newFileEntry.fullPath;
console.log('successful download');
},
function (error) { // error callback for #download
console.log('Error with #download method.', error);
});
});
function(error) { // error callback for #getFile
console.log('Error with #getFile method.', error);
});
})
}

Cordova Contacts Plugin not always showing Contact List

I have the contacts plugin in my app and on one test device (iPhone 5, iOS 9.02) the contact list does not show. And when I do a search, nothing appears. I get no error messages. On some of my other devices like some Android or iOS 8.x devices it does work. This particular problem device has 1200 contacts. Anyone have some suggestions on how to fix? I'll paste the relevant part of my code. Although maybe it is more of a configuration issue?
$scope.getAllContacts = function(searchQuery) {
try {
var opts = { //search options
filter: searchQuery, // 'Bob'
multiple: true, // Yes, return any contact that matches criteria
fields: ['displayName', 'name']
};
if (ionic.Platform.isAndroid()) {
opts.hasPhoneNumber = true; //hasPhoneNumber only works for android.
};
$ionicLoading.show();
$cordovaContacts.find(opts).then(function(contactsFound) {
$scope.contacts = contactsFound;
$ionicLoading.hide();
});
} catch (err) {
alert(err.message);
}
};
$scope.getAllContacts("Ak");
Hi use this to save all contacts in sdcard and display. (default Cordova contacts and file plugin)
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
navigator.contacts.find(["*"], function(contacts) {
// alert("contacts.length = " + contacts.length);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile("contacts.json", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(){
// Success Contacts saved to sdcard as a contacts.json file
// Now get and read the json file
var path = fileSystem.root.getFile("contacts.json", {create:false},gotFileEntry, fail);
// jquery
$.getJSON(path, function (data) {
user = data;
$.each(user, function (index, user) {
var all_item = '<p id="'+user.id+'">'+user.displayName+'</p>';
$('#allcontacts').append(all_item);
});
});
};
writer.write(JSON.stringify(contacts));
}, onError);
}, onError);
}, onError);
}, onError,{"multiple": true});}
function onError(){
alert("Error");
}
You may use navigator.contacts.find, and see if this works in your phone.
For more details
https://github.com/apache/cordova-plugin-contacts

How to schedule data sync in PhoneGap app, retrieving JSON

I am building a PhoneGap app, and currently have setup some datasources that have a JSON feed I pull from, to populate my app with data. Right now, it only pulls that data once, the first time the app is run.
I would like to download data everytime the app first opens, and then if it stays open for longer than 15 minutes, it updates again. The json feed can be queried with a last_mod_day in the URL so it pulls only the data that has changed.
What would be recommended to go about this, and how to check for a WiFi/Data Connection on the phone, and if not it fails quietly?
Below is the code for my current function to grab the feed.
function downloadFileError(evt) {
console.log('downloadFileError: ');
console.log(evt.target.error);
}
function downloadFile(ep) {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile("dummy.json", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
var filename = cordova.file.dataDirectory + 'assets/json/' + ep + '.json';
var fileTransfer = new FileTransfer();
fileEntry.remove();
console.log('looking at ' + filename);
fileTransfer.download(
encodeURI("http://www.myURL.com/theApp?ep=" + ep),
filename,
function(theFile) {
console.log("download complete: " + theFile.toURL());
},
function(error) {
console.log("DLERR: src=" + error.source + " t=" + error.target);
}
);
},
function(evt) {
console.log(evt);
console.log('fn: ' + filename);
}
);
},
downloadFileError);
}
function downloadDynamicPages() {
var deferred = $.Deferred();
var pages = ['setOne','setTwo','setThree','setFour','setFive','setSix'];
var cnt = 0;
var total_pages = pages.length;
//checkConnection();
$.each(pages,function(k,v) {
console.log('looking at ' + v);
downloadFile(v);
cnt++;
if(cnt >= total_pages) {
deferred.resolve('all done with files');
}
});
return deferred.promise();
}
Any help on any part of these questions would help me greatly. If needed, I can answer any questions. Thank you Stack.

jsPDF with Cordova - Adding images

I am trying to generate a PDF using the jsPDF library (https://github.com/MrRio/jsPDF) from within a mobile Cordova app. I am currently testing the app on an Android 4.0.4 device but it also needs to run on Windows mobile 8. The text in the PDF document is shown correctly however any images are scrambled. See image below
I did find this page (https://coderwall.com/p/nc8hia) that seemed to indicate there is a problem with jsPDF displaying images in Cordova (see comments) but the author never posted the follow-up. Has anyone been able to use jsPDF with Cordova and properly add images to the generated PDF? My code is below, any assistance or advice would be greatly appreciated.
function demoReceipt() {
var img = new Image();
img.onError = function() {
alert('Cannot load image: "' + url + '"');
};
img.onload = function() {
createPdf2(img);
};
img.src = 'img/testlogo.png';
}
function createPdf2(myLogo) {
// var doc = new jsPDF('p', 'pt', 'jontype');
var doc = new jsPDF('p', 'pt', 'letter');
doc.setProperties({
title : 'Fueling Receipt',
author : 'Jon Hoffman',
creater : 'Jon Hoffman'
});
doc.addImage(myLogo, 'PNG', 5, 5, 140, 30);
doc.setFontSize(12);
doc.text(10, 40, 'Sample PDF receipt');
doc.setFontSize(8);
doc.text(10, 45, 'Smaller text - new');
var pdfOutput = doc.output();
//NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
//Requires cordova plugin add org.apache.cordova.file
console.log("file system...");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
console.log(fileSystem.root.fullPath);
fileSystem.root.getDirectory("myPDFs", {
create : true,
exclusive : false
}, function(dir) {
fileSystem.root.getFile("myPDFs/test.pdf", {
create : true
}, function(entry) {
var fileEntry = entry;
console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
console.log("writing to file");
writer.write(pdfOutput);
}, function(error) {
console.log(error);
});
}, function(error) {
console.log(error);
});
}, function(error) {
});
}, function(event) {
console.log(evt.target.error.code);
});
}
I solved the issue with help from this blog post: https://coderwall.com/p/nc8hia. There does seems to be significant differences between the 0.90 version used in that post and the version that I am using from https://github.com/MrRio/jsPDF however the solution is pretty much the same.
First off, in the version from MyRio, you can get the PDF generation working without fixing the Blob issue noted in Igor’s post. All you need is to generate the PDF output by calling “doc.ouput()” and then save it using the Cordova filesystem plugin. So I thought I did not have to create the Blob (this is where I was wrong).
Igor (from the coderwall post) responded back to my question with some additional code but when I searched the jspdf.js file from MyRio version, I saw that the code (more compact version) was already in the code on lines 734 – 738:
var data = buildDocument(), len = data.length,
ab = new ArrayBuffer(len), u8 = new Uint8Array(ab);
while(len--) u8[len] = data.charCodeAt(len);
return new Blob([ab], { type : "application/pdf" });
But I also notice that the blob creation code that Igor fixed in his initial post was at the end of this block of code. So I commented out the “return new Blob([ab], { type : “application/pdf”});” line and put in the following code from Igor’s post with minor variable name changes:
try
{
var blob = new Blob([ab], {type: "application/pdf"});
console.debug("case 1");
return blob;
}
catch (e)
{
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder)
{
var bb = new BlobBuilder();
bb.append(ab);
console.debug("case 2");
return bb.getBlob("application/pdf");
}
else if (e.name == "InvalidStateError")
{
// InvalidStateError (tested on FF13 WinXP)
console.debug("case 3");
return new Blob([ab], {type: "application/pdf"});
}
else
{
// We're screwed, blob constructor unsupported entirely
console.debug("Errore");
}
}
Then when I generate that pdfOutput, in my code, I changed
var pdfOutput = doc.output();
to
var pdfOutput = doc.output(“blob”);
and it worked.
I hope this post is able to help out others experiencing the same issues.

How to move captured image in PhoneGap to a folder in sdcard

I am using following code to get image base64 data to display and upload to server.
But i want to save this captured image in sdcard folder. Please help me to do this.
This is necessary for me to get base64 image data because server support only this format. That's why i am using destinationType = 0 (means DATA_URL). I have base64 image data now but how can i save this data to sdcard?
uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail);
function uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail)
{
pictureSource = navigator.camera.PictureSourceType;
if (isSourceCamera)
{
//QUALITY MUST BE LOW TO AVOID MEMORY ISSUES ON IPHONE4 ! (and other low memory phones).
//must resize to make it faster to upload and avoid failure with low memory phones.
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.CAMERA,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
else
{
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.PHOTOLIBRARY,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
}
function onPhotoDataSuccess(imageData)
{
**//I want to smae my image here in sdcard folder.**
var nodeid = localStorage.getItem("user_nodeid");
var modifyImgData = imageData.replace(' ', '+');
document.getElementById('image').src = setLocalStorageImage(localStorage.getItem(nodeid+"image"), modifyImgData);
document.getElementById('profileMenu').src = setLocalStorageImage(localStorage.getItem(nodeid+"smallimage"), modifyImgData);
$.ajax({
type: "POST",
url: appURL+"api/upload/image/" +nodeid+ "/1",
data: "image=" + encodeURIComponent(modifyImgData),
success: function(msg){
//No need to do anything here
if (msg.documentElement.getElementsByTagName("message")[0].childNodes[0].nodeValue != 'success')
onFail('Error in uploading image at server. Please try again.');
}
});
}
function onFail(message){
alert(message);
}
Here is the correct answer to the original question:
How to move captured image in PhoneGap to a folder in sdcard?
function onfail(error,caller){
error = error || '[error]';
caller = caller || '[caller]';
alert('Error > '+caller+" code: "+error.code);
};
/*
Error codes
NOT_FOUND_ERR = 1;
SECURITY_ERR = 2;
ABORT_ERR = 3;
NOT_READABLE_ERR = 4;
ENCODING_ERR = 5;
NO_MODIFICATION_ALLOWED_ERR = 6;
INVALID_STATE_ERR = 7;
SYNTAX_ERR = 8;
INVALID_MODIFICATION_ERR = 9;
QUOTA_EXCEEDED_ERR = 10;
TYPE_MISMATCH_ERR = 11;
PATH_EXISTS_ERR = 12;
*/
function doCameraAPI() {
// Retrieve image file location from specified source
navigator.camera.getPicture(getImageURI, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}; //doCameraAPI
function getImageURI(imageURI) {
//resolve file system for image to move.
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, function(error){onfail(error,'Get Target Image')});
function gotFileEntry(targetImg) {
//alert("got image file entry: " + targetImg.name);
//now lets resolve the location of the destination folder
window.resolveLocalFileSystemURI(POSTPATH, gotDestinationEntry, function(error){onfail(error,'Get Destination Dir')});
function gotDestinationEntry(destination){
// move the file
targetImg.moveTo(destination, targetImg.name, moveSuccess, function(error){onfail(error,'Move Image')});
alert('dest :'+destination.fullPath);
};
function moveSuccess(){
alert('FILE MOVE SUCCESSFUL!');
};
}; //getImageURI
credit to: nbk on the google phonegap group.
Since you have the data in Base64 format you can just use the FileWriter to save the data to disk.
I think you need to capture the image as FILE_URL, and save the image to sdcard first as mentioned by Steven Benjamin above.
Then you can retrive the base64 DATA_URL as
function readFile() { // button onclick function
var gotFileEntry = function(fileEntry) {
console.log("got image file entry: " + fileEntry.fullPath);
fileEntry.file( function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read complete!");
image64.value = evt.target.result;
};
reader.readAsDataURL(file);
}, failFile);
};
window.resolveLocalFileSystemURI("file:///mnt/sdcard/test.jpg", gotFileEntryImage, function(){console.log("* * * onPhotoURISuccess" + failed);});
}

Categories

Resources