Phonegap Cordova FileSystem not persistent on iOS? - ios

I am working on an app for iOS and Android, and I am using Cordovas File plugin to save some data to a file on the device.
This file will contain information about the user, so he/she does not have to log in every time they use the app, so the information has to be there even if the app is exited and relaunched.
On Android this works fine:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 20*1024*1024, app.onFileSystemSuccess, fail);
On Android the data I save is there next time I open the app, but on iOS the file is empty (or not existing).
Does this not work for iOS?
Here is the whole source:
var app = {
initialize: function()
{
this.bindEvents();
},
bindEvents: function()
{
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function()
{
app.initAPP();
},
initAPP: function()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 20*1024*1024, app.onFileSystemSuccess, fail);
},
onFileSystemSuccess: function(FS)
{
FS.root.getDirectory('MyAPPDir', {create:true}, app.gotDir, fail);
},
gotDir: function(Dir)
{
app.appRoot = Dir;
try{
app.appRoot.getFile('authInfo.txt', {create:true}, function(fileEntry){
fileEntry.file(function(file){
alert('Got file authInfo.txt')
var Reader = new FileReader();
Reader.onloadend = function(e){
alert(e.target.result);
if( e.target.result == '' ){
$('#container').load('login.html');
}
else{
document.authInfo = e.target.result;
alert(e.target.result);
alert('You are now auhtorized');
}
}
Reader.readAsText(file);
})
})
} catch(e){
$('#container').load('login.html');
}
},
authUser: function()
{
email = $("#email").val();
password = $("#password").val();
$.ajax({
url: AUTH_URL,
type: 'POST',
data:{
email: email,
password: password
},
success: function(data){
resp = $.parseJSON(data);
if( resp.status == 'success' ){
try{
app.appRoot.getFile('authInfo.txt', {create:true}, function(fileEntry){
fileEntry.createWriter(function(writer){
writer.truncate(0);
writer.onwriteend = function(){
writer.write(resp);
writer.onwriteend = function(){
alert('Wrote '+JSON.stringify(resp)+' to '+fileEntry.toURL());
}
}
});
});
}
catch (e){
alert(e);
}
} else {
alert(resp.message);
}
}
});
}
};
function fail(a){
alert(a);
}
I get this message in iOS:
Wrote {.......myjson.....} to cdvfile://localhost/persistent/MyAPPDir/authInfo.txt
But then when it tries to read it on launch it seems like the file does'nt exist any more, or is empty?

Related

Square Payment Form Request Card Nonce not working in versions of safari

I seem to be having an issue with the requestCardNonce() function for some safari users This is using the Javascript API in my .net MVC application.
The current version I'm testing on appears to be working (13.0.4) but users are still reporting an inability to complete their orders with previous versions of safari. When filling in their information they're able to see the dialog that contains the fields for the Card Name, Number, CVV, and Postal code and expiration date but can't seem to proceed to the next dialog. The onGetCardNonce(event) function seems to be having issues executing properly.
The code I have currently looked like this
if (gateway == "Square Payment Gateway") {
paymentForm = new SqPaymentForm({
applicationId: appId,
inputClass: 'sq-input',
autoBuild: false,
cardNumber: {
elementId: 'sq-card-number',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal'
},
// SqPaymentForm callback functions
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData) {
let errMsg = "";
if (errors) {
// Log errors from nonce generation to the browser developer console.
console.error('Encountered errors:');
errors.forEach(function (error) {
console.error(' ' + error.message);
errMsg += ' ' + error.message;
});
alert('Encountered errors' + errMsg);
return;
}
$("#CardNumber").val(cardData["last_4"]);
$("#squareToken").val(nonce)
$("#form-container").dialog("close");
var isValid = true;
$('#CardName,#CardNumber').each(function () {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "",
"background": ""
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if ($("#Total").val() == "0.00" || $("#Total").val() == "0")
isValid = true;
if (isValid == false) {
$('#PayCreditCard')[0].disabled = false;
}
else {
var targetUrl = $(this).attr("href");
// Open Terms & Conditions
$("#dvTermsConditions").dialog("open");
$("#dvTermsConditions").dialog({
autoOpen: false,
modal: true,
buttons: {
"Proceed": function () {
if ($('#AgreeToTerms').is(':checked')) {
$(':input[type="submit"]').prop('disabled', true);
$(this).dialog("close");
$("#frmCheckOut").submit();
}
else {
alert("You must agree to the terms & conditions.");
}
},
"Cancel": function () {
$('#PayCreditCard')[0].disabled = false;
$(this).dialog("close");
}
}
});
}
}
}
});
paymentForm.build();
function onGetCardNonce(event) {
// Don't submit the form until SqPaymentForm returns with a nonce
event.preventDefault();
// Request a nonce from the SqPaymentForm object
paymentForm.requestCardNonce();
}
function closeCC() {
$("#form-container").dialog("close");
}
}
Originally the issue was that payment form was not found so I moved the definition of that outside the if statement and that seemed to clear up the issue for safari 13.0.4+
Does anyone have suggestions on how to make the square payment form (v2) work on all (or at least the last 3+ years) of versions of Safari (not on mobile)?

Titaniuim: Facebook login event doesn't fire

I am trying to login through facebook.
I have all info in plist and in entitlelements file
So when I click to button it is redirecting safari facebook page and asking to confirm
When I click to OK it doesn’t fire ‘login’ event and it is not logged.
Currently I am testing on iOS 5s Simulator
Here is the code
var fbook = require('facebook');
fbook.appid = <MyAPP_ID>;
fbook.permissions = ['public_profile'];
//fbook.forceDialogAuth = true;
if (fbook.loggedIn) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result)
});
} else {
fbook.addEventListener('login', function(e) {
//alert('try to login');
if (e.success) {
//progress.hide();
params = {
access_token : fbook.accessToken
};
fbook.requestWithGraphPath('/me', params, 'GET', function(e) {
var result = JSON.parse(e.result);
Ti.API.info("Result is : " + e.result);
});
} else if (e.error) {
Ti.API.info("error");
//alert('Error: ' + e.error);
} else if (e.cancelled) {
Ti.API.info("cancelled");
}
});
fbook.authorize();
/*
fbook.addEventListener('logout', function(e) {
fbook.logout();
});*/
}

new transaction is waiting for open operation

I'm creating mobile app using cordova+angular.js+onsenui.
What I want to do is to open pre-populated database, execute select statement and display result as list.
I use litehelpers/cordova-sqlite-ext plugin to manipulate database.
But when I run the app with iOS simulator and see the log in Safari console, "new transaction is waiting for open operation" is logged.
Console log is as below:
database already open: test.db
test1
new transaction is waiting for open operation
DB opened: test.db
My code(index.js) is the following.
angular.module('app').controller('listController', function ($scope) {
var items = [];
ons.ready(function() {
db = sqlitePlugin.openDatabase({name: "test.db", location: 2, createFromLocation: 1});
console.log('test1');
db.readTransaction(function(tx) {
console.log('test2');
var sql = "SELECT id, title, status FROM items";
tx.executeSql(sql, [], function(tx, response) {
for (var i = 0; i < response.rows.length; i++) {
var row = response.rows.item(i);
items.push({title:"Item Title", label:"6h", desc:row.title});
}
}, function(error) {
console.log('SELECT error: ' + error.message);
});
}, errorCB, successCB);
});
function successCB() {
$scope.itemTable = items;
$scope.$apply();
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
$scope.showDetail = function(item) {
console.log('showDetail');
myNavigator.pushPage("detail.html", {item: item});
};
});
Does anyone know how to resolve this?
I appreciate any suggestion and hint.
For someone who has encountered same problem,
I write my solution.
I changed plugin to the following.
litehelpers/Cordova-sqlite-storage
an-rahulpandey/cordova-plugin-dbcopy
And my code is like below.
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
dbcopy();
}
function dbcopy()
{
window.plugins.sqlDB.copy("test.db", 0, copysuccess, copyerror);
}
function copysuccess()
{
//open db and run your queries
//alert('copysuccess');
openDatabase();
}
function openDatabase()
{
db = window.sqlitePlugin.openDatabase({name: "test.db"});
}
function copyerror(e)
{
//db already exists or problem in copying the db file. Check the Log.
console.log("Error Code = "+JSON.stringify(e));
//e.code = 516 => if db exists
if (e.code == '516') {
openDatabase();
}
}
angular.module('app').controller('listController', function ($scope) {
var items = [];
ons.ready(function() {
if (db === null) {
openDatabase();
}
db.transaction(function(tx) {
var sql = "SELECT * FROM items;";
tx.executeSql(sql, [], function(tx, response) {
for (var i = 0; i < response.rows.length; i++) {
var row = response.rows.item(i);
items.push({title:row.title, label:row.label, desc:row.desc});
}
console.log("res.rows.item(0).title: " + response.rows.item(0).title);
}, errorCB);
}, errorCB, successCB);
});
function successCB() {
$scope.itemTable = items;
$scope.$apply();
}
function errorCB(err) {
alert("Error processing SQL: "+err.message);
}
$scope.showDetail = function(item) {
console.log('showDetail');
myNavigator.pushPage("detail.html", {item: item});
};
});

Not able to send push notifications in cloud code

I have saved all the user's location in the installation object. And i have another object named locationObject which gets updated when the current user sends his current location.When it does, i want to compare his current location with all the other saved locations and send push notifications to the users who are nearby.This is my code but this does not seem to work.
//this code should run when the locationObject is updated
Parse.Cloud.afterSave("locationObject", function (request) {
var geoPoint = request.object.get("myCurrentLocation");
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.near("significantLocationUpdate", geoPoint);
pushQuery.limit(100);
pushQuery.find({
success: function(results) {
if (results.length > 0) {
//console.log(JSON.stringify(results));
for (i = 0; i < results.length; 1++) {
Parse.Push.send({
where: pushQuery,
data: {
alert: "some user is nearby"
}
}, {
success: function() {
console.log("push was successfull")
},
error: function(error) {
console.log("sending push failed")// Handle error
}
});
}
} else {
console.log("failure");
}
},
error: function (error) {
console.log("error");
}
});
});
This is how i restructured the code.And it works. Thanks to Paulw11
Parse.Cloud.afterSave("locationObject", function (request) {
var geoPoint = request.object.get("myCurrentLocation");
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.near("significantLocationUpdate", geoPoint);
pushQuery.limit(100);
Parse.Push.send({
where: pushQuery,
data: {
alert: "some user is nearby"
}
}, {
success: function() {
console.log("push was successful");
},
error: function(error) {
console.log("sending push failed")// Handle error
}
});
});

Couchbase-Lite-PhoneGap: I get “Status 400 - Bad request” when I try to create _design document(view)

I've been dealing with Couchbase-Lite-PhoneGap-Plugin.
I've try to create a design document in an Android emulator using REST API. But every time I get status: 400 - Bad request message and I cannot find my mistakes.
My codes are the following;
var cblUrl = "";
var dbName = "user";
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
if(window.cblite) {
window.cblite.getURL(function(err, url) {
if(err) {
console.log("error launching Couchbase Lite: " + err);
} else {
console.log("Couchbase Lite running at " + url);
cblUrl = url;
}
});
} else {
console.log("error, Couchbase Lite plugin not found.");
}
// jQuery Main function
$(function() {
$("#connect").on("tap", function() {
$.ajax({
url: cblUrl + '_all_dbs',
type: 'GET',
success: function (data, textStatus, xhr) {
if (data.indexOf(dbName) == -1) { // db doesn't exist
// create a database (bucket)
$.ajax({
url: cblUrl + dbName,
type: 'PUT',
async: true,
success: function (data, textStatus, xhr) {
console.log(xhr.status);
},
error: function (xhr, statusText, errorThrown) {
console.log(xhr.status);
}
});
} else {
console.log("db exists");
}
},
error: function (xhr, statusText, error) {
console.log(xhr.status);
}
});
}); // #connect tap
// create button tap event
$("#create").on("tap", function() {
var view = {
"language" : "javascript",
"views" : {
"view_user" : {
"map" : "function(doc) {if (doc.username) {emit(doc.username, null)}}"
}
}
}
// ** create VIEW **
$.ajax({
url: cblUrl + dbName + "/_design/users",
type: 'PUT',
data: view,
success: function (data, textStatus, xhr) {
console.log(xhr.status);
},
error: function (xhr, statusText, error) {
console.log(xhr.status);
}
});
});
}); // main jQuery function
}, // onDeviceReady
};
app.initialize();
I had installed my plugin using command of
cordova plugin add com.couchbase.lite.phonegap
However the plugin was beta and a former version at plugins.cordova.io.
And then I've tried to uninstall and re-install plugin using command of
cordova plugin add https://github.com/couchbaselabs/Couchbase-Lite-PhoneGap-Plugin.git
I was able through this way.

Resources