I have to use push notifications in my app, so I followed this tutorial to add the ionic native push.
When I run the app on Android console prints this warning message:
Native: tried calling PushNotification.init, but the PushNotification
plugin is not installed.
I have installed the module with:
$ ionic cordova plugin add phonegap-plugin-push
$ npm install --save #ionic-native/push
How can it be?
My code here:
I added the provider to my app.module.ts:
import { Push } from '#ionic-native/push';
...
providers: [
StatusBar,
SplashScreen,
Services,
Globals,
Push,
Globalization,
Facebook,
GoogleMaps,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler},
{ provide: LOCALE_ID, useValue: 'es' },
{ provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig }
]
And in my app.component.ts I have this:
import { Component } from '#angular/core';
import { Platform, ModalController, MenuController, App, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { TabsPage } from '../pages/tabs/tabs';
import { LogregPage } from '../pages/logreg/logreg';
import { FavoritosPage } from '../pages/favoritos/favoritos';
import { MaptestPage } from '../pages/maptest/maptest';
import { Globals } from '../providers/globals';
import { Services } from '../providers/services';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any;
// rootPage:any = TabsPage;
// rootPage:any = LogregPage;
constructor(public appCtrl: App, public platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public modalCtrl: ModalController,
private push: Push, public menuCtrl: MenuController, public globals: Globals, private services: Services, public alertCtrl: AlertController) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
/// Here we try to start the push services
this.initPushNotification();
/// This checks if user session is open
this.globals.checkSession(
(checked) : void => {
if ( checked ) {
this.rootPage = TabsPage;
} else {
this.rootPage = LogregPage;
}
}
);
});
}
/**
* This method is the same as the example :)
*
*/
initPushNotification() {
if (!this.platform.is('cordova')) {
console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
return;
}
const options: PushOptions = {
android: {
senderID: 'YOUR_SENDER_ID'
},
ios: {
alert: 'true',
badge: false,
sound: 'true'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((data: any) => {
console.log('device token -> ' + data.registrationId);
//TODO - send device token to server
});
pushObject.on('notification').subscribe((data: any) => {
console.log('message -> ' + data.message);
//if user using app and push notification comes
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: 'New Notification',
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'View',
handler: () => {
//TODO: Your logic here
console.log('Push notification recived');
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
console.log('Push notification clicked');
}
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
}
}
EDIT:
After removing and then adding android platform, I get this error runing the app:
BUILD SUCCESSFUL
Total time: 3.207 secs
Subproject Path: CordovaLib
Starting a Gradle Daemon (subsequent builds will be faster)
+-----------------------------------------------------------------
| cordova-android-support-gradle-release: 26.+
+-----------------------------------------------------------------
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
at build_9ug1ggkhhrzygsw0k34tph6ua.run(/Users/[edited path]/platforms/android/build.gradle:143)
FAILURE: Build failed with an exception.
* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35
* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
> For input string: "+"
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 5.408 secs
Error: /Users/[edited path]/platforms/android/gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.
* Where:
Script '/Users/[edited path]/platforms/android/phonegap-plugin-push/tusclases-push.gradle' line: 35
* What went wrong:
A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
> For input string: "+"
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
[ERROR] An error occurred while running cordova run android (exit code 1).
Hi if you want resolve this problem you must follow these instructions (windows10)
ionic cordova platform rm android
rm platform (platforms folder)
rm plugin (plugins folder)
ionic cordova platform add android
ionic cordova build android
AND enjoy it !!!
Related
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 {
}
}
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.
I'm running in the browser an ionic 5 APP using capacitor and I'm trying to use the file transfer functionality. I follow the documentation https://ionicframework.com/docs/native/file-transfer and configure my app using capacitor. Thus running:
npm install cordova-plugin-file-transfer
npm install #ionic-native/file-transfer
ionic cap sync
In my app.module, I registered the providers:
import { FileTransfer } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/file/ngx';
...
providers: [
StatusBar,
SplashScreen,
...
FileTransfer,
File
],
Note that I also installed the native file package, so in total I have the following 4 new packages:
"#ionic-native/file": "^5.27.0",
"#ionic-native/file-transfer": "^5.27.0",
"cordova-plugin-file": "^6.0.2",
"cordova-plugin-file-transfer": "^1.7.1",
My code in the component is:
import { Input, Component } from '#angular/core';
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/file/ngx';
#Component({
selector: 'app-order-detail-order-card',
templateUrl: './order-detail-order-card.page.html'
})
export class OrderDetailOrderCardPage {
#Input() pdfUrl: string;
#Input() orderCardId: string;
constructor(private transfer: FileTransfer, private file: File) { }
public downloadFile(): void {
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(this.pdfUrl, this.file.applicationDirectory + `${orderCardId}.pdf`).then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
}
When I run the app in the browser, I get the following warning and I'm not sure whether the file should donwload somewhere?
common.js:284 Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
Even if I don't get the file, I would be expecting to see the "download complete" message. It's not very clear to me as to whether I have to configure something else in my app to be able to run it locally or I have to use this functionality ONLY in either the emulator or the device itself.
What else needs to be configured to get this to work?
common.js:284 Native: tried calling SplashScreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
this means that you are using the browser emulator which doesn't have any splashscreen, you can totally ignore that warning ( you won't get it using a simulator or a real device).
You should paste the html section of that page too, because probably the download doesn't start because an incomplete url and it doesn't proceed with the "then()"
maybe i'm wrong, but it can be possible.
I’m trying to find a way to open the settings/preferences app with capacitor but I’m unsuccessful.
App.canOpenUrl({ url: 'com.apple.Preferences' }) is failing with error message -canOpenURL: failed for URL: "com.apple.Preferences" - error: "Invalid input URL"
I’m not sure if I’m doing it wrong or if it’s even possible with capacitor to open native app…?
this article shows how to open the facebook app, but nothing about native app
There's now a capacitor plugin for this, capacitor native settings.
It's similar to the cordova plugin but you have to call the correct function for each platform (iOS or Android) instead of using a single function for both.
for someone with the same problem
Install:
cordova-open-native-settings
$ npm install cordova-open-native-settings
$ npm install #ionic-native/open-native-settings
$ ionic cap sync
app.module.ts
// ...
import { OpenNativeSettings } from '#ionic-native/open-native-settings/ngx';
#NgModule({
declarations: [
// ...
],
entryComponents: [
// ...
],
imports: [
// ...
],
providers: [
// ...
OpenNativeSettings,
],
bootstrap: [AppComponent]
})
export class AppModule {}
whatever.page.ts
// ...
import { OpenNativeSettings } from '#ionic-native/open-native-settings/ngx';
#Component({
selector: 'app-whatever',
templateUrl: './whatever.page.html',
styleUrls: ['./whatever.page.scss'],
})
export class PopoverComponent implements OnInit {
constructor(
// ...
private nativeSettings: OpenNativeSettings
) { }
phoneSettings() {
this.nativeSettings
.open('settings')
.then( res => {
console.log(res);
})
.catch( err => {
console.log(err);
})
}
}
I have added Ionic Secure Storage plugin (to store authentication tokens) into my Ionic project, and it works properly locally when running cordova run browser (so that cordova is loaded as a plaform).
However, when I open my project in Ionic DevApp and Ionic View on Android (works correctly on iOS), it fails silently whenever I try to retrieve the saved token.
Here is my code:
// ... unrelated imports omitted
import {Platform} from "ionic-angular";
import {SecureStorage, SecureStorageObject} from "#ionic-native/secure-storage";
#Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponent {
constructor(private platform: Platform,
private secureStorage: SecureStorage) {
}
ngOnInit() {
this.getToken().then(token => {
// ... do something with the retrieved token
});
}
getToken() {
if (this.platform.is('cordova')) {
/**
* Code below silently fails in Ionic View and Ionic Dev App
* on Android (works correctly on iOS)
*/
return this.platform.ready().then(() =>
return this.secureStorage.create('cp_secure_storage')
.then((storage: SecureStorageObject) => {
return storage.get('TOKEN_NAME')
.then(token => {
console.log(token);
return token;
}, () => null);
});
});
} else {
return Promise.resolve(localStorage.getItem('TOKEN_NAME'));
}
}
}
I have Ionic error monitoring turned on and it catches no errors.
Plugin version:
"#ionic-native/secure-storage": "4.5.3",
"cordova-plugin-secure-storage": "^2.6.8"