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 {
}
}
Related
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 am trying to implement local notifications using capacitor.
first I installed plugin using below commands,
npm install #ionic-native/local-notifications
npm install cordova-plugin-local-notification
Then in my .js file, I did add below code
import { Plugins } from '#capacitor/core';
And
scheduleNotification = () => {
Plugins.LocalNotifications.schedule({
notifications: [
{
title: "Title",
body: "Body",
id: 1,
schedule: { at: new Date(Date.now() + 1000 * 5) },
sound: null,
attachments: null,
actionTypeId: "",
extra: null
}
]
});
console.log('scheduled notifications');
}
I tried everything, but I can't see any local notification on my iPhone 6s running iOS 12.
When I check Xcode logs, I can see Scheduled notification with id 1.
cordova-plugin-badge (0.8.8)
cordova-plugin-device (2.0.3)
cordova-plugin-local-notification (0.9.0-beta.2)
I had the same issue, I set my notification id with an UUID but it did not work. I solved it in setting my notification id with new Date().getTime().
It was issue regarding id pass in your result.
PushNotifications.addListener('pushNotificationReceived',
async (notification: any) => {
console.log(notification);
const notifs = await LocalNotifications.schedule({
notifications: [
{
title: notification.title,
body: notification.body,
id: new Date().getTime(),
schedule: { at: new Date(Date.now() + 1000 * 5) },
sound: this.platform.is("android")
? "file://sound.mp3"
: "file://beep.caf",
attachments: null,
actionTypeId: "",
extra: notification
}
]
});
}
);
For the ios, I think, it is not supported yet.
For android, try to request permission.
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"
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 !!!
We are developing ionic app with mfp8.0. We are using the following code to connect with mfp server,
var Messages = {
// Add here your messages for the default language.
// Generate a similar file with a language suffix containing the translated messages.
// key1 : message1,
};
var wlInitOptions = {
// Options to initialize with the WL.Client object.
// For initialization options please refer to IBM MobileFirst Platform Foundation Knowledge Center.
onSuccess:function(){alert('success')},
onFailure:function(){alert('fail')}
};
function wlCommonInit() {
app.init();
}
var app = {
//initialize app
"init": function init() {
app.testServerConnection();
},
//test server connection
"testServerConnection": function testServerConnection() {
WL.App.getServerUrl(function (url) {
});
WLAuthorizationManager.obtainAccessToken()
.then(
function (accessToken) {
alert('accessToken '+JSON.stringify(accessToken));
isPushSupported();
},
function (error) {
alert('Error '+error);
}
);
},
}
function isPushSupported() {
MFPPush.isPushSupported(
function(successResponse) {
alert("Push Supported: " + successResponse);
registerDevice();
}, function(failureResponse) {
alert("Failed to get push support status");
}
);
}
function registerDevice() {
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
MFPPush.registerDevice(
{"phoneNumber":""}, // workaround due to a defect in the current release of the product. An empty "phoneNumber" property must be passed at this time.
function(successResponse) {
alert("Successfully registered");
},
function(failureResponse) {
alert("Failed to register");
alert("Failed to register device:" + JSON.stringify(failureResponse));
}
)
);
}
We can able to connect with mfp server. But, We unable register device for push notifcations. We are getting the following error,
"com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushException:Response:Status=404, Text:Error 404: SRVE0295E: Error reported: 404\r\n, Error Message : Not Found"
(or)
"com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushException:Response:Status=500,Text:{\"errorCode\":\"UNEXPECTED_ERROR\",\"errorMsg\":\"Unexpected Error Encountered\"}, Error Message : Unexpected Error Encountered"
Actually, We are getting this error recently. Before that the same code was working fine for us.
Anyone help will be Appreciated!!!
Change the function of Register Device accordingly.
Please go through the link:
https://github.com/MobileFirst-Platform-Developer-Center/PushNotificationsCordova/blob/release80/www/js/index.js
function registerDevice() {
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
MFPPush.registerDevice(
null,
function(successResponse) {
alert("Successfully registered");
},
function(failureResponse) {
alert("Failed to register");
alert("Failed to register device:" + JSON.stringify(failureResponse));
}
)
);
}
Your code snippets do not show how did you try to register your application to the push service...
Did you follow the instructions of the push tutorial and looked at the sample push applications before opening a question?
See the tutorials and samples, here: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/notifications/handling-push-notifications/