I know this question is already asked but I have problem in that solution which is not answered there.
I used this plugin but this gives me error:
var success = function (app_list) { alert(JSON.stringify(app_list)); };
var error = function (app_list) { alert("Oopsie! " + app_list); };
Applist.createEvent('', '', '', '', '', success, error)
How can I remove this error? I downloaded it running:
npm i cordova-plugin-applist
Error message:
Cannot find name 'Applist'
Add
import * as Applist from 'cordova-plugin-applist2/www/Applist.js';
import { Platform } from '#ionic/angular';
to your component .ts file
Then to use it in probably constructor
constructor(public platform: Platform) {
platform.ready().then(
function(){
if(platform.is('android') && !platform.is('mobileweb')){
var success = function(app_list) {
//success function
console.log(app_list);
};
var error = function(app_list) {
//error
console.log("An Error occured while fetching App Lists");
console.error(app_list);
};
//for the date parameters, any date is okay,
//the first date should be in the past
Applist.createEvent('', '', '', new Date(1999, 10, 11, 12, 12, 12, 12), new Date(), success, error);
}
}
);
}
Related
Razor pay works properly when opening in a browser but when i convert the project into an android app, external page which is supposed to be opened to submit OTP doesn't show up. I understand i need an inAppBrowser to open the link but it is not controlled by me. Razorpay will open the link automatically when the user chooses card payment or internet banking. How to solve this? please help!
window-ref.service.ts
import {Injectable} from '#angular/core';
// declare var cordova:any;
export interface ICustomWindow extends Window {
__custom_global_stuff: string;
}
function getWindow(): any {
return window;
}
#Injectable({
providedIn: 'root'
})
export class WindowRefService {
get nativeWindow(): ICustomWindow {
return getWindow();
}
}
app.component.ts
constructor(private winRef: WindowRefService) {
this._window = this.winRef.nativeWindow;
}
private _window: ICustomWindow;
public rzp: any;
public options: any = {
key: 'KEY', // add razorpay key here
name: 'Bunto Couriers Pvt. Ltd.',
description: 'Delivery Fee',
amount: this.price*100, // razorpay takes amount in paisa
prefill: {
name: '',
email: '', // add your email id
},
image: 'https://isell-bunto.000webhostapp.com/assets/img/loader.png',
notes: {},
theme: {
color: '#3880FG'
},
handler: this.paymentHandler.bind(this),
modal: {
ondismiss: (() => {
this.zone.run(() => {
// add current page routing if payment fails
this.toastr.error("Payment Error!");
})
})
}
};
initPay(): void {
this.rzp = new this.winRef.nativeWindow['Razorpay'](this.options);
this.rzp.open();
}
paymentHandler(res: any) {
this.zone.run(() => {
// add API call here
console.log(res);
});
}
this is a pop up window which opens fine in both browser and in android app
this external page doesn't show up in the app
in the app, this is as far as it goes. external url doesn't open after this stage
I'm not sure how the Javascript library will work while we don't have the control over showing it using the InAppBrowser.
For this, I really suggest to use the native Cordova Razorpay plugin for more compatibility and stability: https://github.com/razorpay/razorpay-cordova
You can check their sample apps (Cordova and Ionic)
Add command: cordova plugin add https://github.com/razorpay/razorpay-cordova.git --save
var options = {
description: 'Credits towards consultation',
image: 'https://i.imgur.com/3g7nmJC.png',
currency: 'INR',
key: 'rzp_test_1DP5mmOlF5G5ag',
order_id: 'order_7HtFNLS98dSj8x',
amount: '5000',
name: 'foo',
theme: {
color: '#F37254'
}
}
var successCallback = function(success) {
alert('payment_id: ' + success.razorpay_payment_id)
var orderId = success.razorpay_order_id
var signature = success.razorpay_signature
}
var cancelCallback = function(error) {
alert(error.description + ' (Error '+error.code+')')
}
RazorpayCheckout.on('payment.success', successCallback)
RazorpayCheckout.on('payment.cancel', cancelCallback)
RazorpayCheckout.open(options)
I've built a small alert service (wrapper for Angular AlertController) in my Ionic 4 project, it works perfectly when I view the project in "ionic serve" (browser), "ionic cordova emulate" (on my connected phone), "ionic cordova build android" (installing the app-debug APK manually on my phone) however when I build the release version of the app using "ionic cordova build android --prod --release" the "message" part of the Alert does not show. The header (title) and the buttons show and work fine still, but the message does not appear.
Here is my method which creates and presents the alert:
/**
* "Confirm" with callback or "Cancel" alert
*/
async confirmOrCancelAlert(title, message, callback) {
const alert = await this.alertController.create({
header: title,
message: message,
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
}, {
text: 'Confirm',
handler: () => {
callback();
}
}
]
});
await alert.present();
}
This is the code which called the method shown above, which is called from a button click:
/**
* Answer questions button event click
*/
answerQuestions() {
if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';
this.alertService.confirmOrCancelAlert('You are early!', message, () => {
this.doAnswerQuestions();
});
} else {
this.doAnswerQuestions();
}
}
Here are two images showing the message messing from the release build but showing in the serve / emulate / debug builds:
Many thanks in advance for any and all advice.
I think it's a timing problem. when you call confirmOrCancelAlert() the timeTo is not prepared yet. so the type of message will be undefined.
try this:
answerQuestions() {
if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';
setTimeout(() => {
this.alertService.confirmOrCancelAlert('You are early!', message, () => {
this.doAnswerQuestions();
});
}, 50);
} else {
this.doAnswerQuestions();
}
}
try this:
async confirmOrCancelAlert(title, myMessage, callback) {
const alert = await this.alertController.create({
header: title,
message: myMessage,
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
}, {
text: 'Confirm',
handler: () => {
callback();
}
}
]
});
await alert.present();
}
change the name to myMessage to make it different than property name. message: message will cause a problem I think I had the same problem last year. check it out and inform me of the results.
I'm working on an ionic3 application. I need to take an image from the user either by camera or gallery, first saves it to the local directory then upload the image to the server. I used the following step by step tutorial: https://devdactic.com/ionic-2-images/
Uploading the photo is working like a charm, but while saving the image to the local directory and save the path on local storage, after retrieving from storage it shows the following error: .
As it's obvious it complains about Not allowed to load local resource.
Next, I started to google for the solution, and I found this solution in StackOverflow and this in GitHub. As they both suggested, the problem is with cordova-plugin-ionic-webview, so I need to downgrade the version. When I tried their solution, the uploading and showing the image to the user is working perfectly, however, it creates problem other parts of the application which is loading data from asset no matter what; images, fonts. Shows the following error .Next I found a solutionf for the problem in GitHub here, as it suggested and accepted by most users we need to use the latest version of **cordova-plugin-ionic-webview **, which of course it would cause the first problem for me.
I'm gonna upload the codes here as well.`
getImage() {
this.presentActionSheet();
} //end getImage
public uploadImage() {
console.log('Uploading the image');
console.log(this.lastImageL);
var targetPath = this.pathForImage(this.lastImage);
console.log(targetPath);
var url = "https://dev.raihan.pomdev.net/wp-json/raihan/v1/profilePhoto";
var filename = this.lastImage;
console.log(' targetPath : ', targetPath);
console.log('File Name : ', filename)
console.log(url, " IS the URL");
var options = {
fileKey: "image",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params: {
'image': filename,
'user_id': 79
}
};
const fileTransfer: TransferObject = this.transfer.create();
this.loading = this.loadingCtrl.create({
content: 'منتظر باشید',
});
this.loading.present();
// Use the FileTransfer to upload the image
fileTransfer.upload(targetPath, url, options).then(data => {
this.loading.dismissAll()
this.presentToast(' . عکس شما موفقانه ذخیره شد');
this.storage.set("Profile_Photo", targetPath).then((data) => {
console.log('response of uploading the image ', data);
console.log('Target Path ', targetPath);
console.log('In set storage ', targetPath);
$("#Photo").attr("src", targetPath);
$("#Photo2").attr("src", targetPath);
console.log('myphoto ', targetPath);
});
}, err => {
this.loading.dismissAll()
this.presentToast('مشکلی در قسمت ذخیره کردن عکس شما وجود دارد ' + err);
console.log('error sending the image');
console.log(err);
});
}
public takePicture(sourceType) {
var options = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imagePath) => {
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}, (err) => {
this.presentToast('Error while selecting image.');
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CaptureImagePage');
}
private createFileName() {
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
return newFileName;
}
// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
this.lastImage = newFileName;
this.uploadImage();
}, error => {
this.presentToast('Error while storing file. ' + error);
});
}
private presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 5000,
position: 'center'
});
toast.present();
}
// Always get the accurate path to your apps folder
public pathForImage(img) {
if (img === null) {
return '';
} else {
return cordova.file.dataDirectory + img;
}
}
public presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select Image Source',
buttons: [
{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
`
Now I'm confused which version of **cordova-plugin-ionic-webview ** I should use? Is there someone who could help me?
Note: Thanks for your patience to read all the questions.
I would try to use the latest version of the WebView if possible, and then use the window.Ionic.WebView.convertFileSrc() method on the file:/// path before putting it on a page for display. Those tips can be seen here:
https://ionicframework.com/docs/building/webview
Cordova and Capacitor apps are hosted on a local HTTP server and are
served with the http:// protocol. Some plugins, however, attempt to
access device files via the file:// protocol. To avoid difficulties
between http:// and file://, paths to device files must be rewritten
to use the local HTTP server. For example, file:///path/to/device/file
must be rewritten as http://://path/to/device/file
before being rendered in the app.
For Cordova apps, the Ionic Web View plugin provides a utility
function for converting File URIs:
window.Ionic.WebView.convertFileSrc(). There is also a corresponding
Ionic Native plugin: #ionic-native/ionic-webview.
Here is a sample method I use, which works fine in the 4.x webview:
getNormalizedUrl(path: string): SafeResourceUrl {
let newPath = this.domSanitizer.bypassSecurityTrustUrl(
window.Ionic.WebView.convertFileSrc(path));
return newPath;
}
I have the error like in question, when I'm trying to design my application to call native.camera, I see my console in ionic 3 project, I saw this error :
Native : tried calling Camera.getPicture, but Cordova is not available. Make sure to include cordova.js or run in a device / simulator.
Here is the code that I used to called native camera.
This is the code in my problem.html
<button class="logoCamera" ion-button (click)="presentActionSheet()">
<ion-icon name="camera" ></ion-icon>
This is the code in my problem.ts
import { File } from '#ionic-native/file';
import { Transfer, TransferObject} from '#ionic-native/transfer';
import { FilePath } from '#ionic-native/file-path';
import { Camera } from '#ionic-native/camera';
public presentActionSheet(){
let actionSheet = this.actionSheetCtrl.create({
title: 'Select Image',
buttons: [
{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
public takePicture(sourceType){
//Create option for the Camera dialog
var options = {
quality: 100,
sourceType : sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
//Get the data of an image
this.camera.getPicture(options).then((imagePath) => {
//special handling for android lib
if(this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1 );
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/')+ 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}, (err) => {
this.presentToast('Error while selecting Image.');
});
}
//Create a new name for image
private createFileName() {
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
return newFileName;
}
//copy image to local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
this.lastImage = newFileName;
}, error => {
this.presentToast('Error while storing file.');
});
}
private presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 3000,
position: 'middle'
});
toast.present();
}
public pathForImage(img){
if (img === null) {
return '';
} else {
return cordova.file.dataDirectory + img;
}
}
public uploadImage() {
//destination URL
var url = "";
//file to upload
var targetPath = this.pathForImage(this.lastImage);
//file name only
var filename = this.lastImage;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params: {'fileName': filename}
};
const fileTransfer: TransferObject = this.transfer.create();
this.loading = this.loadingCtrl.create({
content: 'Uploading...',
});
this.loading.present();
//use FileTransfer to upload image
fileTransfer.upload(targetPath, url, options).then(data => {
this.loading.dismissAll()
this.presentToast('Image successful uploaded.');
}, err => {
this.loading.dismissAll()
this.presentToast('Error while uploading file.');
});
}
When I run ionic serve, everything is smooth, no error, no nothing.
But when I click my button to access natve camera, the error shows, please help me figure out the problem, I check a lot of web, and none of it solve my question.
After I try run ionic cordova run ios --simulator, there are error coming out, but I am pretty sure that this error does not exist before I run this command.
May I know how to solve this problem ??
The error message is pretty accurate here:
Native : tried calling Camera.getPicture, but Cordova is not available. Make sure to include cordova.js or run in a device / simulator.
Running ionic serve does not include cordova.js nor does it run your application in a simulator or on a device which is why you get the error. You can fix it either by running your application on the device or simulator:
ionic cordova run android/ios --device/--simulator
Or by adding the browser platform:
cordova platform add browser
And running the browser platform:
ionic cordova run browser
I have a problem that I couldn't figure out!(I'm, kinda new at this though)
I am trying to run a cordova app on android platform(using a Mac and eclipse-luna), the build is successful, but when I'm trying to login with facebook nothing happens and I get this error in the LogCat:
"Uncaught ReferenceError: facebookConnectPlugin is not defined"
I tried everything I could think of(including lots of posts here at stackoverflow) and nothing solved it.
I would really appreciate any help!
the js code -
var facebookLogin=function()
{
var fbLoginSuccess3 = function (userData)
{
var str=JSON.stringify(userData);
var id=userData["authResponse"].userID;
$.mobile.loading('show');
var promise = $.ajax({
type: 'GET',
url: "https://graph.facebook.com/"+id+"? fields=first_name,last_name,email,picture.width(450).height(450)&access_token="+userData["authResponse"].accessToken,
dataType: 'json'
});
promise.fail( function() {
$.mobile.loading('hide');
});
promise.done( function(result)
{
//alert(JSON.stringify(result));
var first_name=result.first_name;
var last_name=result.last_name;
var email=result.email;
var profileImgUrl=result.picture.data.url;
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
profileImgUrl=profileImgUrl.replaceAll("&","^");
//alert(id+" "+first_name+" "+last_name+" "+email+" "+profileImgUrl);
facebookLoginHandler(id,first_name,last_name,email,profileImgUrl);
});
}
//alert("before login");
facebookConnectPlugin.login(["public_profile","email"],fbLoginSuccess3,function (error) { alert("" + error) });
}
cordova_plugins.js -
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/com.phonegap.plugins.facebookconnect/facebookConnectPlugin.js",
"id": "com.phonegap.plugins.facebookconnect.FacebookConnectPlugin",
"clobbers": [
"facebookConnectPlugin"
]
},
module.exports.metadata =
// TOP OF METADATA
{
"com.phonegap.plugins.facebookconnect": "0.11.0",
"org.apache.cordova.camera": "0.3.4",
"org.apache.cordova.inappbrowser": "0.5.4",
"org.apache.cordova.splashscreen": "0.3.5",
"org.apache.cordova.file": "1.3.3",
"org.apache.cordova.file-transfer": "0.5.0"
}
// BOTTOM OF METADATA
});