Ionic3 - Email Composer - Object(...) is not a function - ionic-framework

For Ionic, I'm trying something with emails. So an user presses a button and goes to an email app to send an email with a set 'to', 'subject' and 'body'.
I followed the Ionic doc for EmailComposer : https://ionicframework.com/docs/native/email-composer
So I installed the plugin, followed the 'usage'.
import { EmailComposer } from '#ionic-native/email-composer/ngx';
constructor(private emailComposer: EmailComposer) { }
...
this.emailComposer.isAvailable().then((available: boolean) =>{
if(available) {
//Now we know we can send
}
});
let email = {
to: 'max#mustermann.de',
cc: 'erika#mustermann.de',
bcc: ['john#doe.com', 'jane#doe.com'],
// attachments: [],
subject: 'Cordova Icons',
body: 'How are you? Nice greetings from Leipzig',
isHtml: true
}
// Send a text message using default options
this.emailComposer.open(email);
Only when I press the button. I get error :
ERROR TypeError: Object(...) is not a function
at EmailComposer.open (index.js:58)
I don't know the reason for this. I tried this in a fresh ionic3 project, but I still got the same error.

EmailComposer from #ionic-native/email-composer/ngx is not supporting in Ionic 3. It is supporting in Ionic 4. You need to install EmailComposer from #ionic-native/email-composer which supports for Ionic 3.
Install EmailComposer using below command.
npm install --save #ionic-native/email-composer#4

The problem is you are telling the function what to do but aren't calling the function:
this.emailComposer.isAvailable().then((available: boolean) => {
if(available) {
//Now we know we can send
}
});
You have to name the function and after it, tell it what to do:
sendEmail() {
this.emailComposer.isAvailable().then((available: boolean) => {
if (available) {
}
});
let email = {
to: 'email#domain',
subject: '',
body: '',
isHtml: true
};
this.emailComposer.open(email);
}

Related

OneSignal issue for Ionic 6 & Capacitor

I'm trying to set OneSignal for push notifications on devices.
I did the step by step to setup methods which are shown in the OneSignal Documentation, but no luck.
I also did the official Ionic - Capacitor - Cordova methods to setup OneSignal, with no luck again.
This is the first method I did, following Ionic official Docs:
app.module.ts
...
import { OneSignal } from '#awesome-cordova-plugins/onesingal';
#NgModule({
...
providers: [OneSignal]
});
I created a PushService where I include methods from OneSignal.
push.service.ts:
import { OneSignal } '#awesome-cordova-plugins/onesignal';
export class PushService {
constructor ( private signal: OneSignal ) {}
start (): void {
this.signal.startInit ( 'MY_ONESIGNAL_APP_ID', 'FIREBASE_ID' );
this.signal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
...
this.signal.endInit();
}
}
I call "start" method on my app.component.ts, initializing on this.platform.ready...
And when I test on my device, the answer from debug is "plugin_not_installed" OneSignal
Second method I use, following instructions from the Official OneSignal Docs "Ionic & Capacitor"
Directly I put methods on my "start" in push.service.ts, I didn't call it on app.module.ts because is a function:
import { OneSignal } from 'onesignal-cordova-plugin';
export class PushService {
constructor () {}
start (): void {
OneSignal.setAppId ( 'ONESIGNAL_APP_ID' );
...
OneSignal.setNotificationWillShowInForegroundHandler ( ( d ) => console.log ( d ) );
}
}
In this case, the error is "TypeError: Cannot read properties of undefined (reading 'setAppId')"
So, any of those methods is not working.
My system info develop is:
Ionic:
Ionic CLI : 6.18.1 (C:\Users\user\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 6.0.1
#angular-devkit/build-angular : 13.1.2
#angular-devkit/schematics : 12.2.13
#angular/cli : 13.1.2
#ionic/angular-toolkit : 5.0.3
Capacitor:
Capacitor CLI : 3.3.3
#capacitor/android : 3.3.3
#capacitor/core : 3.3.3
#capacitor/ios : not installed
Utility:
cordova-res : not installed globally
native-run : 1.5.0
System:
NodeJS : v16.13.1 (C:\Program Files\nodejs\node.exe)
npm : 8.2.0
OS : Windows 10
I think you need to install the plugin - this is what I have in package.json
"onesignal-cordova-plugin": "^3.0.1"
And import like this -
import OneSignal from 'onesignal-cordova-plugin';
And also in angular.json add this part with allowedCommonJsDependencies
{
"projects": {
"app": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"allowedCommonJsDependencies": [
"onesignal-cordova-plugin"
]
}
}
}
}
}
}
The official One Signal docs need improvement but they helped me to find the path to get push notifications working with Capacitor 3 and Ionic 6 using Vue on web mobile and also on Android. This is working on my projects.
The points of attention are these:
If you'll use mobile push or native push, you have to initialize Onesignal detecting the platform.
You also have to include Onesignal service worker js files somewhere they could be located by the browser.
// Call this function when your app start
function OneSignalInit() {
OneSignal.setAppId("xxxxx-xxxxxx-xxxxxx"); //Your APP ID
OneSignal.setNotificationOpenedHandler(function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
});
OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
console.log("User accepted notifications: " + accepted);
});
}
if (getPlatforms().includes("capacitor")) {
OneSignalInit();
} else {
window.OneSignal = window.OneSignal || [];
window.OneSignal.push(function () {
// You have to include some JS files from Onesignal as the docs say to do
// Place them in a place findable by the browser when the URL is resolved
window.OneSignal.SERVICE_WORKER_PARAM = { scope: '/assets/js/onesignal/' };
window.OneSignal.SERVICE_WORKER_PATH = 'assets/js/onesignal/OneSignalSDKWorker.js'
window.OneSignal.SERVICE_WORKER_UPDATER_PATH = 'assets/js/onesignal/OneSignalSDKUpdaterWorker.js'
window.OneSignal.init({
appId: "xxxxx-xxxxx-xxxxx", //Your APP ID
safari_web_id: "web.onesignal.auto.xxxxxxxxxxx",
notifyButton: {
enable: false,
},
subdomainName: "odontoenlace",
promptOptions: {
slidedown: {
prompts: [
{
type: "push", // current types are "push" & "category"
autoPrompt: true,
text: {
/* limited to 90 characters */
actionMessage: "Nos gustaría enviarte notificaciones para que estés al tanto de eventos en tu perfil.",
/* acceptButton limited to 15 characters */
acceptButton: "Aceptar",
/* cancelButton limited to 15 characters */
cancelButton: "Cancelar"
},
delay: {
pageViews: 0,
timeDelay: 1
}
}
]
}
}
});
});
}
After all that, you can use this code to detect if Onesignal is recognized and get your Onesignal user_id also known as player_id. Again, checking if you are on web or native.
if (getPlatforms().includes("capacitor")) {
OneSignal.setAppId("xxxxx-xxxxx-xxxxxx"); // Your APP ID
OneSignal.getDeviceState((stateChanges) => {
console.log(
"OneSignal getDeviceState: " + JSON.stringify(stateChanges)
);
if (stateChanges && stateChanges.hasNotificationPermission) {
console.log("Player ID: " + stateChanges.userId);
} else {
console.log("Push notifications are disabled");
}
});
} else {
console.log("Platform is not capacitor");
is_push_supported.value =
window.OneSignal.isPushNotificationsSupported();
if (is_push_supported.value) {
if (!getPlatforms().includes("capacitor")) {
window.OneSignal.getUserId((userId) => {
console.log("Player ID: " + userId);
});
}
}
}
Finally, if you're compiling your app, Capacitor's default settings for release mode, suppress externals Onesignal libraries so check on your build.gradle file that you have disabled proguard, and minifyEnabled is set to false. The best way is to leave empty the relase object
buildTypes {
release {
}
}

Ionic v5 web media capture with capacitor - cordova_not_available

I am building an app with Ionic 5, Capacitor 2 and Angular 11.
I need to capture video and audio using the media capture cordova plugin.
I installed the following modules:
npm install cordova-plugin-media-capture
npm install #ionic-native/media-capture
And added MediaCapture to the providers of my app module.
Then I call mediaCapture.captureVideo() to retrieve a video ; unfortunately an exception is thrown when testing on a browser: cordova_not_available
The github repo states this plugin is web-compatible, and its sources have a browser implementation. However the window.navigator.device.capture is missing to make this plugin work.
Is it a bad configuration from my side? Or this cordova plugin wouldn't be compatible with capacitor?
I made a repro : https://stackblitz.com/edit/ionic-v5-media-capture-capacitor?file=src/app/app.component.ts
Thank you for your help
I wrote a regular Angular version for the web, if anyone need it:
async browserCapture() {
const stream: MediaStream = await navigator.mediaDevices.getUserMedia(this.constraints);
const recorder = new MediaRecorder(stream, {mimeType: 'ogg'});
const chunks: Blob[] = [];
recorder.ondataavailable = (event: BlobEvent) => {
if (event.data && event.data.size > 0) {
chunks.push(event.data);
this.zone.run(() => {
this.recordChunks = [...chunks];
this.cd.markForCheck();
});
}
};
this.recorder.onstop = () => {
this.zone.run(() => {
stream.getTracks().forEach(t => t.stop());
if (chunks?.length) {
this.upload(new Blob(chunks, {type: 'ogg'})); // use the blob result
}
});
};
recorder.start(500);
}

How to use Pushwoosh in Ionic 5 project with capacitor

Hi everyone I am migrating an app from ionic 1 to ionic 5 and I need to integrate the pushwoosh notification service, my project was started not using cordova, instead I use capacitor and I can't find information about how to integrate this service to an ionic 5 application.
Please, we already know that you can use cordova but when using the cordova plugin add pushwoosh-cordova-plugin#8.0.0 it gives you the following message:
Current working directory is not a Cordova-based project.
because as I said before it is a capacitor project not a cordovan project, Btw I already use ionic integrations enable cordova
So... if anyone can help us, It would be very helpful.
OK guys after many hours trying to integrate Pushwoosh into an ionic 5 application for me it was impossible,
If you set everything up correctly, the following will happen:
Your app will connect to Pushwoosh correctly
Your app will correctly register your device in pushwoosh
But your app will not listen to the listeners offered by the official Pushwoosh documentation
document.addEventListener('push-receive',
function (event) {
var message = (<any>event).notification.message;
var userData = (<any>event).notification.userdata;
alert("Push message received: " + message);
console.info(JSON.stringify((<any>event).notification));
//dump custom data to the console if it exists
if (typeof (userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
}
);
This does not work in an ionic 5 app 👆🏽
This does work:
import { Component, OnInit } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed,
} from '#capacitor/core';
const { PushNotifications } = Plugins;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
ngOnInit() {
console.log('Initializing HomePage');
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermission().then(result => {
if (result.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
},
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotification) => {
alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
},
);
}
}
I tried to combine Pushwoosh with the capacitor but the tokens of the devices that are generated are different so I still didn't get my notifications.
At the end of the day and after many hours and days of work I have no other option than to use firebase and now everything is going much better.

Change FCM sender ID

I had setup push notification in my App using the following command:
ionic cordova plugin add phonegap-plugin-push --variable SENDER_ID="1234567890"
Which added the below code to my package.json
"phonegap-plugin-push": {
"SENDER_ID": "1234567890"
}
Now the issue is I have to change this sender ID to something else and I want to know how to do this, also I have the below code in my project to set up the options for push notification.
const options: PushOptions = {
android: {
senderID: '218580369028'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
Is this as simple as just replacing the sender ID with what I want in package.json and in the above code. Or do I have to do something else for this. Any help is greatly appreciated.

Ionic native Transfer plugin's `file.dataDirectory` shows error

I'm going to use the Ionic native Transfer plugin as shown below.
Problem is here this.file.dataDirectory.It shows error like [ts] Property 'dataDirectory' does not exist on type 'File'..Can you tell me what is the solution for this?
download() {
const fileTransfer: TransferObject = this.transfer.create();
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
Oh.. My bad :(
I have to install File plugin too :D
$ ionic cordova plugin add cordova-plugin-file --save
$ npm install --save #ionic-native/file