cordova-plugin-apple-watch plugin issue - cordova-plugins

Hi I am calling the init method of cordova-plugin-apple-watch plugin in our cordova application , but it is not returning to neither successhandler or errorhandler.
isWatchPairingExists: function() {
var deferred = new Deferred();
console.log("gdfgd");
applewatch.init(successHandler, errorHandler, "group.com.company.app");
function successHandler() {
console.log("rrrr");
alert("binding exist");
return deferred.resolve(true);
}
function errorHandler() {
console.log("ewrwrwr");
alert("binding does not exist");
return deferred.resolve(false);
}
return deferred.promise;
}
};
I am really grateful , if anyone can help on this.

Related

How to return from then of a Future in dart

I have a function which does some asynchronous operations and I want to return the status of the operation back to the caller. How can I achieve this?
Future<bool> setData() async {
Firestore.instance.collection("test").document('$id').setData({
'id': 'test'
}).then((onValue) {
print('Data set success');
return true;
}).catchError((onError) {
print('Data set Error!!!');
return false;
});
}
//Calling
final status = await setData();
if(status){
//do success
}
But this function complains that it doesn't end with a return statement. What is the logical mistake I'm making here?
You miss a return in your setData function
return Firestore.instance....

Worklight JSON store encryption of collection not working in ios

I am using JSONStore in my application to store some sensitive data. To encrypt collection,we are passing options with username and password as mentioned below. In android so far its working fine but in ios devices we are getting blank page while retrieving data from collection (working fine in simulators). I'm not getting any errors also.Without passing options in ios, its working fine. Has anybody faced similar issue?
factory('todoJsonStorage',['$q', function ($q) {
'use strict';
var COLLECTION_NAME = 'Users';
var collections = {
Users: {
searchFields: {UserId: 'string', password: 'string'}
},
};
var options = {};
//Optional username
options.username = 'testuser';
//Optional password
options.password = 'test123';
//Optional local key generation flag
options.localKeyGen = true;
var inited = false;
//checks if inited and if not inits
function initJSONStore(){
var initDeferred = $q.defer();
if (inited){
initDeferred.resolve();
} else {
//Initialize the collection
WL.JSONStore.init(collections,options).then(function () {
console.log("-> JSONStore init successful");
initDeferred.resolve();
}).fail(function (errorObject) {
console.log("-> JSONStore error: " + errorObject.msg);
});
return initDeferred.promise;
};
}
return {
get: function () {
var deferred = $q.defer();
initJSONStore().then(function(){
WL.JSONStore.get(COLLECTION_NAME).findAll().then(function (res) {
if (res.length > 0){
deferred.resolve(JSON.parse(res[0].json.data || '[]'));
} else {
deferred.resolve(res);
}
}).fail(function (errorObject) {
console.log("JSONStore findbyid error: " + errorObject.msg);
});
});
return deferred.promise;
},
put: function (todos) {
WL.JSONStore.get(COLLECTION_NAME).clear();
WL.JSONStore.get(COLLECTION_NAME).add({data:JSON.stringify(todos)});
}
};
}])
If you are using iOS 10, you must enable the Keychain Sharing Capability, otherwise this should work out-of-the-box.

How to prevent multiple instances in Electron

I do not know if this is possible but I might as well give it a chance and ask.
I'm doing an Electron app and I'd like to know if it is possible to have no more than a single instance at a time.
I have found this gist but I'm not sure hot to use it. Can someone shed some light of share a better idea ?
var preventMultipleInstances = function(window) {
var socket = (process.platform === 'win32') ? '\\\\.\\pipe\\myapp-sock' : path.join(os.tmpdir(), 'myapp.sock');
net.connect({path: socket}, function () {
var errorMessage = 'Another instance of ' + pjson.productName + ' is already running. Only one instance of the app can be open at a time.'
dialog.showMessageBox(window, {'type': 'error', message: errorMessage, buttons: ['OK']}, function() {
window.destroy()
})
}).on('error', function (err) {
if (process.platform !== 'win32') {
// try to unlink older socket if it exists, if it doesn't,
// ignore ENOENT errors
try {
fs.unlinkSync(socket);
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
net.createServer(function (connection) {}).listen(socket);;
});
}
There is a new API now: requestSingleInstanceLock
const { app } = require('electron')
let myWindow = null
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
// Create myWindow, load the rest of the app, etc...
app.on('ready', () => {
})
}
Use the makeSingleInstance function in the app module, there's even an example in the docs.
In Case you need the code.
let mainWindow = null;
//to make singleton instance
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.focus()
}
})
if (isSecondInstance) {
app.quit()
}

breeze observableArray binding - are properties observable?

I have a viewmodel which consists of a list(foreach loop) of DoctorPrices and when clicking on an item in the list it open up a CRUD form on the side. However when i update the values on the CRUD the observableArray that is bound to the foreach is not refreshing? (although the values are updates in the DB correctly)
From my data access module i call the following query.
function getDoctorServices(doctorId) {
var query = breeze.EntityQuery
.from('DoctorPrices')
.where('DoctorID', 'eq', doctorId).orderBy('ListOrder');
return manager.executeQueryLocally(query);
}
In my viewmodel i have the following code:
this.services = ko.computed(function() {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
});
services is bound using a foreach loop (not posting here as the code is simple and works)
When i click on a one of the DoctorPrices it gets the data as follows and places it in an observable:
this.selectedPrice = function (data, event) {
self.currentService(data);
self.showEdit(true);
};
I then bind selectPrice to a simple form that has the properties on it to be modified by the user. I then call manager.SaveChanges().
This results in the following problem: the value is being updated correctly but the GUI / Original List that is bound in the foreach is not being updated? Are the properties in breeze not observables? What is the best way to work with something like this.
I thought of a workaround and changing the code with something like this:
doctorList.viewModel.instance.currentDoctorID.subscribe(function() {
self.services([]);
self.services(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
});
But i feel that clearing the array in that way is sloppy and not the right way of doing things specially with long lists.
Can someone please point me in the right direction on how to bind observableArray properties properly so they are updated?
Additional code my VM Component:
function services() {
var self = this;
this.showForm = ko.observable(false);
this.currentService = ko.observable();
this.services = ko.observableArray(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
this.title = ko.observable();
doctorList.viewModel.instance.currentDoctorID.subscribe(function() {
self.services([]);
self.services(doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID()));
self.showDetails(false);
});
this.show = function (value) {
self.showForm(value);
};
this.showDetails = ko.observable(false);
this.addNewService = function() {
self.currentService(doctorServices.createService(doctorList.viewModel.instance.currentDoctorID()));
console.log(self.currentService().entityAspect.entityState);
self.showDetails(true);
};
this.showDelete = ko.computed(function() {
if (self.currentService() == null)
return false;
else if (self.currentService().entityAspect.entityState.isDetached()) {
self.title('Add new service');
return false;
} else {
self.title('Edit service');
return true;
}
});
this.deleteService = function() {
self.currentService().entityAspect.setDeleted();
doctorServices.saveChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
};
this.closeDetails = function () {
doctorServices.manager.rejectChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
self.showDetails(false);
};
this.selectService = function (data, event) {
self.currentService(data);
self.showDetails(true);
};
this.saveChanges = function () {
console.log(self.currentService().entityAspect.entityState);
if (self.currentService().entityAspect.entityState.isDetached()) {
doctorServices.attachEntity(self.currentService());
}
console.log(self.currentService().entityAspect.entityState);
doctorServices.saveChanges();
doctorList.viewModel.instance.currentDoctorID.notifySubscribers();
self.currentService.notifySubscribers();
self.showDetails(true);
};
}
return {
viewModel: {
instance: new services()
},
template: servicesTemplate,
};
Below is my Breeze Data Class:
define('data/doctorServices', ['jquery', 'data/dataManager', 'knockout','mod/medappBase', 'breeze', 'breeze.savequeuing'], function ($, manager, ko,base, breeze, savequeuing) {
var services = ko.observableArray([]);
return {
attachEntity:attachEntity,
getServices: getServices,
services: services,
manager:manager,
getDoctorServices: getDoctorServices,
getServiceById: getServiceById,
createService:createService,
hasChanges: hasChanges,
saveChanges: saveChanges
};
function getServices() {
var query = breeze.EntityQuery.from("DoctorPrices");
return manager.executeQuery(query).then(function (data) {
services(data.results);
}).fail(function (data) {
console.log('fetch failed...');
console.log(data);
});;
}
function getDoctorServices(doctorId) {
var query = breeze.EntityQuery
.from('DoctorPrices')
.where('DoctorID', 'eq', doctorId).orderBy('ListOrder');
var set = manager.executeQueryLocally(query);
return set;
}
function getServiceById(serviceId) {
return manager.createEntity('DoctorPrice', serviceId);
//return manager.getEntityByKey('DoctorPrice', serviceId);
}
function handleSaveValidationError(error) {
var message = "Not saved due to validation error";
try { // fish out the first error
var firstErr = error.innerError.entityErrors[0];
message += ": " + firstErr.errorMessage;
base.addNotify('error', 'Could not save.', message);
} catch (e) { /* eat it for now */ }
return message;
}
function hasChanges() {
return manager.hasChanges();
}
function attachEntity(entity) {
manager.addEntity(entity);
}
function createService(doctorId) {
return manager.createEntity('DoctorPrice', { DoctorPricingID: breeze.core.getUuid(), DoctorID:doctorId }, breeze.EntityState.Detached);
};
function saveChanges() {
return manager.saveChanges()
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
base.addNotify('success', 'Saved.', 'Your updates have been saved.');
}
function saveFailed(error) {
var reason = error.message;
var detail = error.detail;
if (error.innerError.entityErrors) {
reason = handleSaveValidationError(error);
} else if (detail && detail.ExceptionType &&
detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
// Concurrency error
reason =
"Another user, perhaps the server, " +
"may have deleted one or all of the settings." +
" You may have to restart the app.";
} else {
reason = "Failed to save changes: " + reason +
" You may have to restart the app.";
}
console.log(error);
console.log(reason);
}
}
});
Please note this is my frist attempt at both a data class and VM. At the moment i am relying heavily on clearing the array ([]) and using notifySubscribers to make the array refresh :(
I bet you're missing an observable somewhere. I can't tell because you keep hopping from property to property whose definition is not shown.
For example, I don't know how you defined this.currentService.
I'm confused by this:
this.services = ko.computed(function() {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
});
Why is it a ko.computed? Why not just make it an observable array.
self.service = ko.observableArray();
// ... later replace the inner array in one step ...
self.service(doctorServices.getDoctorServices(
doctorList.viewModel.instance.currentDoctorID()));
I urge you to follow the observability trail, confident that your Breeze entity properties are indeed observable.
vm.selectedPrice = ko.dependentObservable(function () {
return doctorServices.getDoctorServices(doctorList.viewModel.instance.currentDoctorID());
}, vm);
vm is ur model on which u applied bindings , try this it will work.

ChildBrowser onLocationChange not working

Basically I am using ChildBrowser on iOS, it works almost perfectly. The problem is the onLocationChange, onClose and onOpenExternal don't work and for the life of me I can't figure out why.
Any help would be much appreciated
<script type="text/javascript" charset="utf-8">
var cb;
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
console.log("Device Ready");
cb = ChildBrowser.install();
}
function openChildBrowser(url)
{
console.log("New Url"+url);
try {
cb.showWebPage(url);
cb.onLocationChange = function(loc){ root.locChanged(loc); };
cb.onClose = function(){root.onCloseBrowser()};
cb.onOpenExternal = function(){root.onOpenExternal();};
}
catch (err)
{
alert(err);
}
}
function onCloseBrowser()
{
console.log("closed");
alert("In index.html child browser closed");
}
function locChanged(loc)
{
console.log("new loc:"+loc);
childBrowser.close();
alert("In index.html new loc = " + loc);
}
function onOpenExternal()
{
console.log("new loc:");
alert("In index.html onOpenExternal");
}
</script>
I have tried window.plugins.childBrowser.onLocationChange ect.
take out the root.onlocationChange, no need to have that.
Encapsulate the locChanged, onCloseBrowser, onOpenExternal into a main function to make correct calls because childbrowser when it´s opened doesn't have the scope of locChanged
for example:
var facebook = function() {
locChanged = funciton() {
//your code here
}
return {
"init": init,
"locChanged": locChanged,
"onCloseBrowser": onCloseBrowser,
"onOpenExternal": onOpenExternal
}
}();

Resources