trying to store image as base64 and using it - ios

I have a block of code that I found online and it seems to be working and not working at the same time. I think its probably my lack of understanding but I cant seem to get it to work the way I want it.
selectPicture() {
let context = imagepicker.create({
mode: "single" // use "multiple" for multiple selection
});
var imageBase64
context
.authorize()
.then(function() {
return context.present();
})
.then(function(selection) {
selection.forEach(function(selected) {
imageSourceModule.fromAsset(selected).then((imageSource) => {
imageBase64 = imageSource.toBase64String("jpg",60);
console.log("Image saved successfully!")
console.log(imageBase64)
console.log("test test") //runs fine
this.image = "~/assets/images/account/camera.png" //cant seem to run
console.log("test test 2")
}).catch(function (e) {
// process error
console.log("got error 1")
});
})
}).catch(function (e) {
// process error
console.log("got error 2")
});
},
Within the imageSourceModule.fromAsset(selected).then((imageSource), I was trying to save the base64 info in another variable but cant seem to do anything within other than console log a string. When I run this.image = "~/assets/images/account/camera.png" (just a placeholder, even calling a method does not work too) for example it catches an error.
What could the problem be? thank you!
UPDATE
I changed console.log("got error 1") to log the actual update and what i got was:
undefined is not an object (evaluating 'this.image = "~/assets/images/account/camera.png"')*
I now think that theres a problem with my understanding calling variable outside. My variable 'image' is within the script at
data() {
return {
image : ""
}
}

first of all check what this variable is, because you do not use es6 arrow functions, so this is probably not the vue instance.
the second thing: when you change vue-variables asynchronously use the $set method, like: this.$set(this, 'image', '~/assets/images/account/camera.png')

Related

Cypress: intercept and modify part of the response

Based on Cypress docs, I want to modify a field on the response and leave everything else unchanged, after first loading the fixture. I know I could easily do this with 2 fixtures but I would not like to duplicate it for a simple field change. I tried variations of the following code but to no success. Any ideas?
it('Should have the correct values in monthly', () => {
cy.intercept('POST', `**/full`, (req) => {
req.continue(res => {
res.body.data.monthly = 5000;
res.send(res);
})
});
cy.fixture('calculator/monthlyRepayment.json').as('fixtures:monthlyRepayment');
cy.route('POST', `**/full`, '#fixtures:monthlyRepayment').as(`request:fullData`);
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$5000.00');
})
I left a comment, but this will solve your problem, too. You'll want to modify your fixture data before using it:
it('Should have the correct values in monthly', () => {
cy.fixture('calculator/monthlyRepayment.json').then((json) => {
json.monthly = 5000;
cy.intercept('POST', '**/full', json);
// cy.visit called somewhere here
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$5000.00');
});
})

React Native: RNIap.getPurchaseHistory().then runs infinately

The project is at this Github Repository. The file with the code is at components/Soundboard.js
This code was working previously, but now it looks like the promise is running forever. It looks like neither the resolve function, nor the reject function are executing because if I uncomment all the commented lines below and call the function askForPurchase() the only things printed to the console are
an object that looks like "_40": 0, "_55": {"_40": 0, "_55": null, "_65": 0, "_72": null}, "_65": 3, "_72": null} for the line console.log(RNIap.getPurchaseHistory())
and then the word end.
The buyProduct() function also is no longer initializing an IAP.
const buyProduct = function(){
RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})
}
const askForPurchase = function(){
if (!store.getState().purchase){
//console.log(RNIap.getPurchaseHistory())
RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}
}
EXTRA
This code was working a few months ago and I even pulled a commit(1b9cb81f229680e173ce910892dddedc632c1651, comment: "Made the seal pic more cartoony") from that time to test out. After pulling this commit, I deleted my node_modules and pods, and cleaned my build folder, but the askForPurchase() and buyProduct() functions no longer work in that commit either.
I am testing this on a real iPhone SE running ios 13.6.1
I created a sandbox tester if you need to test it out, but I don't think you'll need it
email: rniapsandbox#gmail.com
pw: Somepassword1
hello #Sam problem is async await problem they are not able to get value because they are not waiting to get data before getting data its firing without data and it was returning promise so you have to use async function
so your code be like
const buyProduct = async()=>{
await RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})}
const askForPurchase = async()=>{
if (!store.getState().purchase){
//console.log(await RNIap.getPurchaseHistory())
await RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}}
You will need to change from
console.log(RNIap.getPurchaseHistory())
to
console.log(await RNIap.getPurchaseHistory())

Firebase database remove() "is not a function"

This code works:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once('value')
.then(function(snapshot) {
console.log(snapshot.val());
})
It logs the object and its key.
This code doesn't work:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).remove()
.then(function(snapshot) {
console.log("Removed!");
})
The error message is:
TypeError: firebase.database(...).ref(...).orderByChild(...).equalTo(...).remove is not a function
The documentation makes remove() look simple. What am I missing?
You can only load data once you know its specific location in the JSON tree. To determine that location, you need to execute the query and loop through the matching results:
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
child.ref.remove();
console.log("Removed!");
})
});
If you only want to log after all have been removed, you can use Promise.all():
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(child) {
promises.push(child.ref.remove());
})
Promise.all(promises).then(function() {
console.log("All removed!");
})
});
This is Frank's first code block with another closure. Without the closure the record is removed from the database but then there's an error message:
Uncaught (in promise) TypeError: snapshot.forEach(...).then is not a function
Adding a closure fixes the error message.
firebase.database().ref($scope.language).orderByChild('word').equalTo($scope.word).once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
child.ref.remove();
}); // a closure is needed here
}).then(function() {
console.log("Removed!");
});

iOS screenshot with cordova is not in the photos library

I'm using the cordova screenshot plugin : https://github.com/gitawego/cordova-screenshot to take a screenshot in my iPhone using this code :
navigator.screenshot.save(function (error, res) {
if (error) {
console.log('Screenshot error');
console.error(error);
} else {
console.log('screenshot ok', res.filePath);
}
}, 'jpg', 50, 'project-X-result');
It seems to work (i have no error) but I can't find the screenshot in the Photos Library. Is it possible to save it in this library?
How should I do? Using another plugin to move the file? (where should it be moved exactly?) Editing the plugin to save it directly in the library? (where should it be saved exactly?)
I just ran through the same problem. It took several days but I figured out how to do it.
It does involve another plugin Canvas2Image plugin. I didn't think it would work, but I was desperate and it did work in the end. Here's how I did it.
If you are getting the console.log for screenshot ok, then you are in good shape. The next thing you will need to do is install Canvas2Image with your CLI like so:
cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git
(or replace 'cordova' with 'phonegap' if you use that instead.)
Next, you will need to add a function (in this case saveImageToPhone()) that calls the plugin you just added to your project. This function will be called from your navigator.screenshot.save() function you already have. We will add that function call to your screenshot.save success block, right after the console.log line.
The key here is using that filePath property that we get back in the success block; That's our absolute path to the image we just saved to the temp folder in iOS. We will simply pass that path to the second function and let it do its work.
Here's those two functions from my code:
function saveScreen(){
navigator.screenshot.save(function(error,res){
if(error){
console.error(error);
}else{
console.log('ok',res.filePath);
var MEsuccess = function(msg){
console.info(msg);
} ;
var MEerror = function(err){
console.error(err);
};
saveImageToPhone(res.filePath, MEsuccess, MEerror);
}
},'jpg',90);
}
function saveImageToPhone(url, success, error) {
var canvas, context, imageDataUrl, imageData;
var img = new Image();
img.onload = function() {
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
try {
imageDataUrl = canvas.toDataURL('image/jpeg', 1.0);
imageData = imageDataUrl.replace(/data:image\/jpeg;base64,/, '');
cordova.exec(
success,
error,
'Canvas2ImagePlugin',
'saveImageDataToLibrary',
[imageData]
);
}
catch(e) {
error(e.message);
}
};
try {
img.src = url;
}
catch(e) {
error(e.message);
}
}
Now just call the first function from wherever you wish.
If it works, you'll get a console.log right after your filePath readout that says
IMAGE SAVED!
Be careful, you might overwrite the same screenshot if you use a name as a screenshot.save parameter (after your jpg and quality parameters). My app needs to save different screenshots and have them all available later; by removing the name parameter and allowing the OS to name the file I was able to achieve just that.
I hope that helps you out, I know it caused me a lot of trouble...

Using forge.prefs always returns undefined

I'm trying to use forge.prefs to store variables but nothing seems to be saving.
I am using the following:
var all = forge.prefs.keys(function(keysArray){ return keysArray},
function(content){return content});
forge.logging.log(all);
But this always returns undefined
I am also having the same issue with setting, nothing seems to be working.
var set = forge.prefs.set(key,value,function(){},function(content){return content;});
forge.logging.log(set);
Again returns undefined and no error or anything.
Am I doing something wrong?
Using the docs found here
UPDATE
I won't to do something like the following:
var get = forge.prefs.get(key,
function(value){return value;},
function(error){forge.logging.log(error);
});
if(get){
// do something here
}else{
// do something here
}
Those methods are asynchronous which means that subsequent code might be executed before the callback success and error functions are returned. All subsequent code that relies on the outcome of this should run within the callback:
forge.prefs.keys(function(keysArray){ // success
forge.logging.log(keysArray);
// subsequent code relying on a positive outcome here ...
},
function(error){ // error
forge.logging.log('Something bad happened: ' + error);
});
forge.prefs.set(key, value, function(){ // success
forge.logging.log(key + ' was properly set);
// subsequent code relying on a positive outcome here ...
},
function(error){ // error
forge.logging.log('Something bad happened: ' + error);
});
UPDATE: use this to achieve the updated part of your question:
var get;
forge.prefs.get(key, function(value){ // success
get = value;
forge.logging.log('Found value: ' + get);
// subsequent code here ...
},
function(error){ // error
forge.logging.log('Something bad happened: ' + error);
});
It appears you're not returning anything in the forge.pref.set success function. Your return content; is in the error function so if it's not throwing an error you won't return anything.
Try this:
var set = forge.prefs.set(key,value,function(){ return value; },function(content){return content;});
forge.logging.log(set);

Resources