OneSignal dont send notification to specific device - android

I want send notification to specific user, i can get the id but when i try to send a notification to these id doesn't work.
In android does not send either success or error notification, and ios send a "index.html null" notification.
The notifications arrive the same device from where I send them, none arrives at the device where I want to send them.
this is app.component.js:
let notificationOpenedCallback = function(jsonData) {
let alert =alertCtrl.create({
title: jsonData.notification.payload.title,
subTitle: jsonData.notification.payload.body,
buttons: ['OK']
});
alert.present();
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};
window["plugins"].OneSignal
.startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
});
and with this code i send de notification
window['plugins'].OneSignal.getIds(function(ids) {
let notificationObj = { contents: {"en": "Han hecho un nuevo pedido"},
heading: { "en": "Domi-Trustik" },
include_player_ids: [this.idadmin]
};
window['plugins'].OneSignal.postNotification(notificationObj,
function(successResponse) {
console.log("Notification Post Success:", successResponse);
alert("enviado:" + JSON.stringify(successResponse));
},
function (failedResponse) {
console.log("Notification Post Failed: ", failedResponse);
alert("error" + JSON.stringify(failedResponse));
}
);
});
Is in Ionic 2

Its de same error of my other onesignal question, the plugin its no work fine for some functions so its better use native ionic version:
import { OneSignal } from '#ionic-native/onesignal';
constructor(public one: OneSignal)
this.one.getIds().then((ids) => {
let notificationObj = {
include_player_ids: [this.idadmin],
contents: {en: "Han hecho un nuevo pedido"}};
window['plugins'].OneSignal.postNotification(notificationObj,
function(successResponse) {
console.log("Notification Post Success:", successResponse);
alert("enviado:" + JSON.stringify(successResponse));
},
function (failedResponse) {
console.log("Notification Post Failed: ", failedResponse);
alert("error" + JSON.stringify(failedResponse));
}
);
});

Related

Unable to fetch title and message from push notification when app is in BACKGROUND

I am trying to build react-native app which has push notification implemented using react-native-push-notification. Now, when the app is in 'foreground', I am able to handle the notification.title and notification.message and displaying in an alert in the app (Through, PushNotification.configure's onNotification). When the app in in 'background', I am able to receive notification and when I click it, the app gets opened up or comes to the foreground. Here, I want to fetch the same notification.title and notification.message to display, but don't see these fields in notification JSON (notification.data is also empty). Following is the code from PushNotification.configure's onNotification:
onNotification: function (notification) {
console.log('NOTIFICATION:', JSON.stringify(notification));
if (notification.foreground) {
if(notification.userInteraction) {
Alert.alert("Title:" + notification.title + " Message:" + notification.message);
} else {
PushNotification.localNotification({
id: notification.id,
autoCancel: true,
title: notification.title,
message: notification.message,
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
});
PushNotification.cancelLocalNotifications({id: notification.id});
}
} else {
console.log("notification.data:", JSON.stringify(notification.data));
if(notification.userInteraction) {
console.log("Showing modal with notification details...");
}
}
},
Thank you for your time to look into this.

How to resolve Nifty cloud send push notification error from monaca (android)?

I have implemented nifty cloud for push notification service in monaca platform(android).
I can receive push notification send from nifty cloud mobile backend.
document.addEventListener("deviceready", function () {
console.log("app is ready");
window.NCMB.monaca.setDeviceToken(
"a111111111111111111111111111111111111111111111111111111111111111",//Application Key
"b111111111111111111111111111111111111111111111111111111111111111", //Client Key
"22222222222" //fcm sender id
);
}, false);
But i also need to send push notification from android. For this this i am following this
// "Application key" and "Client Key"
var ncmb = new
NCMB("a111111111111111111111111111111111111111111111111111111111111111", "b111111111111111111111111111111111111111111111111111111111111111"); //
var push = new ncmb.Push();
$scope.pushSend = function () {
push.set({
"immediateDeliveryFlag": true,
"target": ["android"],
"message": "Please input your test messge",
"deliveryExpirationTime": "3 day"
});
push.send()
.then(function (message) {
console.log(message);
})
.catch(function (err) {
console.log(err);
});
};
Now, I'm getting this error
this is my request header
I can see that in my request header X-NCMB-Apps-Session-Token is missing.
So why X-NCMB-Apps-Session-Token is not present in my request header and how to solve 404 (Not Found) problem.

Get notification when a user wants to add data to the database

I'm about to begin working on a recipe Android app for my college final project, and I want users to be able to add recipes to the database. However, I don't want the data to be added right away, but I'd like to receive a notification whenever someone wants to add a recipe, so I can confirm it myself. I'm using back{4}app by the way.
How can I do such a thing in a not-so-complicated way? I was thinking to create an admin account for myself in the app itself, but is there any way to send the notifications to said account? I also want to be able to confirm recipe addition with a simple "Confirm" button from within the app, so will this require me to create an additional class for pending recipes? Will I need an admin account in any case?
all this can be achieve by using cloud code.
Parse.cloud.define("addRecipe", function(request, response) {
const query = new Parse.Query("recipe");
query.set("name", "name");
query.save({
success function(result) {
response(result);
//call push notification function from client or from cloud code when the error is nil
},
error: function(result, error) {
response(error);
}
});
});
this is an example of push notifications using cloud code.
push notification are not allow anymore from the client due to secure reason.
you should be subscribe to this channel
Parse.Cloud.define("pushsample", function (request, response) {
Parse.Push.send({
channels: ["channelName"],
data: {
title: "Hello!",
message: "Hello from the Cloud Code",
}
}, {
success: function () {
// Push was successful
response.sucess("push sent");
},
error: function (error) {
// Push was unsucessful
response.sucess("error with push: " + error);
},
useMasterKey: true
});
});
you should also implement some logic to your app in order to display recipes confirm by admin.
var recipe = Parse.Object.extend("recipe");
var query = new Parse.Query(recipe);
query.equalTo("confirm", true);
query.find({
success: function(results) {
//it will display recipes confirmed
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
});
you should also setup a admin system in your app or a website

implementing push notification in ionic app

I am trying to implement push notification in ionic app for Android.
I have followed step by step guide from http://docs.ionic.io/v1.0/docs/push-from-scratch.
When I am running my app on android phone, then the registered users are listed in apps.ionic.io. So user registration is working fine.
But device registration is not working.
It is giving error Cannot read property 'pushNotification' of undefined
This is my code at the top of app.js
angular.module('starter', ['ionic','ngCordova',
'ionic.service.core',
'ionic.service.push',
'starter.controllers',
'starter.services'])
.config(['$ionicAppProvider', function($ionicAppProvider) {
// Identify app
$ionicAppProvider.identify({
// The App ID (from apps.ionic.io) for the server
app_id: '',
// The public API key all services will use for this app
api_key: '',
// Set the app to use development pushes
// dev_push: true
gcm_id: ''
});
}])
Here is the code in of my controller
.controller('DashboardCtrl', function($scope,$localstorage, WildfireService, CommonUtilityService,PushNotificationService,$ionicPopup, $ionicLoading) {
PushNotificationService.identifyUser();
PushNotificationService.pushRegister();
})
Here is my services.js
.service('PushNotificationService', function($q, $ionicUser, $ionicPush) {
var PushNotificationService = this;
PushNotificationService.identifyUser = function(){
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Technews',
bio: 'Hardcoded for now'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
//alert('Identified user ' + user.name + '\n ID ' + user.user_id);
return true;
});
},
PushNotificationService.pushRegister = function(){
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
alert(notification);
return true;
}
});
}
})
Can any one tell me where is the error or what I am missing?
I have added these in index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="lib/ionic-service-core/ionic-core.js"></script>
<script src="lib/ionic-service-push/ionic-push.js"></script>
Finally push notification is working for me. I moved the function call of pushRegister from controller to identifyUser function. So here is the new working code for me.
Controller code
.controller('DashboardCtrl', function($scope,$localstorage, WildfireService, CommonUtilityService,PushNotificationService,$ionicPopup, $ionicLoading) {
PushNotificationService.identifyUser();
})
Here is new services.js
.service('PushNotificationService', function($q, $ionicUser, $ionicPush) {
var PushNotificationService = this;
PushNotificationService.identifyUser = function(){
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Technews',
bio: 'Hardcoded for now'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
//alert('Identified user ' + user.name + '\n ID ' + user.user_id);
PushNotificationService.pushRegister();
return true;
});
},
PushNotificationService.pushRegister = function(){
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
alert(notification);
return true;
}
});
}
})
I don't know about this new Ionic push notifications. I succesfully implemented push notifications in my Ionic App with ngCordova's push plugin for both Android an iOS (http://ngcordova.com/docs/plugins/pushNotifications/) just by following the examples there. The key is to put the code in the .run module in app.js.
Here is the code:
angular.module('notPush', ['ionic','notPush.controllers','notPush.factorys','ngCordova','ionic.service.core'])
.run(function($ionicPlatform, $rootScope, $http, $cordovaPush) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
// Manejador de notificaciones push para Android
if (ionic.Platform.isAndroid()){
var androidConfig = {
"senderID": "94XXXXXXXXXX", // ID HERE
"ecb": "window.casosPush"
};
try{
var pushNotification = window.plugins.pushNotification;
} catch (ex){
}
// Llamada en caso de exito
var successfn = function(result){
alert("Success: " + result);
};
// Llamada en caso de error
var errorfn = function(result){
window.alert("Error: " + result);
};
// Llamada de casos de notificacion push
window.casosPush = function(notification){
switch (notification.event){
case 'registered':
if (notification.regid.length > 0){
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
alert(JSON.stringify([notification]));
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
};
try{
// Llamada de registro con la plataforma GCM
pushNotification.register(successfn,errorfn,androidConfig);
} catch(notification){
}
}
})
Just remember to install the plugin with
cordova plugin add https://github.com/phonegap-build/PushPlugin.git

Android PushNotifications with PushPlugin on emulator

I've been following this sample to get android pushNotifications (with GCM) working on an android emulator.
After $cordovaPush.register(config) I get Ok as response. But it never runs my callback [$scope.$on('$cordovaPush:notificationReceived'].
And in consequence I never get my registration ID.
I've created a google API project. And I'm using that project Id in the config.senderID when calling $cordovaPush.register(config).
I've also registered a gmail account into my emulator.
I guess I have 2 questions.
1.Is it possible to get (and register) push notifications on an android emulator?
why don't I get a $cordovaPush:notificationReceived event that calls my callback?
app.controller('AppCtrl', function($scope, $cordovaPush, $cordovaDialogs, $cordovaMedia, $cordovaToast, ionPlatform, $http) {
$scope.notifications = [];
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
$scope.register();
});
// Register
$scope.register = function () {
var config = null;
if (ionic.Platform.isAndroid()) {
config = {
"senderID": "12834957xxxx"
};
}
$cordovaPush.register(config).then(function (result) {
console.log("Register success " + result);
$cordovaToast.showShortCenter('Registered for push notifications');
$scope.registerDisabled=true;
}, function (err) {
console.log("Register error " + err)
});
}
$scope.$on('$cordovaPush:notificationReceived', function (event, notification) {
console.log(JSON.stringify([notification]));
if (ionic.Platform.isAndroid()) {
handleAndroid(notification);
}
});
// Android Notification Received Handler
function handleAndroid(notification) {
// ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too
// via the console fields as shown.
console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart);
if (notification.event == "registered") {
$scope.regId = notification.regid;
storeDeviceToken("android");
}
else if (notification.event == "message") {
$cordovaDialogs.alert(notification.message, "Push Notification Received");
$scope.$apply(function () {
$scope.notifications.push(JSON.stringify(notification.message));
})
}
else if (notification.event == "error")
$cordovaDialogs.alert(notification.msg, "Push notification error event");
else $cordovaDialogs.alert(notification.event, "Push notification handler - Unprocessed Event");
}
The fix is a lot simpler than it seems.
I changed from:
$scope.$on('$cordovaPush:notificationReceived', function (event, notification) {
to:
$scope.$on('pushNotificationReceived', function (event, notification) {
while debugging I noticed this on ng-cordova.js:
angular.module('ngCordova.plugins.push', [])
.factory('$cordovaPush', ['$q', '$window', '$rootScope', function ($q, $window, $rootScope) {
return {
onNotification: function (notification) {
$rootScope.$apply(function () {
$rootScope.$broadcast('pushNotificationReceived', notification);
});
},
That means that it's doing a broadcast for 'pushNotificationReceived'. Not 'notificationReceived' as documented.
I have the same problem. It has been reported in ngCordova github, but no replies yet.
I managed to fix it. I know it's not a good solution if you are using angular but it's the only way I'm able to catch the register Id.
Inside the config object you must specify the 'ecb':
var androidConfig = {
"senderID": "388573974286",
"ecb": "function_to_be_called"
};
Put outside the controller the function:
window.function_to_be_called = function (notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
};
Even if you update the event name as you said, I also have another problem, which says: processmessage failed: message: jjavascript:angular.element(document.queryselector('[ng-app]')).injector().get('$cordovapush').onnotification({"event":"registered"...
It happens when angular doesn't find 'ng-app' and it returns 'undefined' angular.element(document.querySelector('[ng-app]'))
So to solve this, you can set manually your 'ecb' like this:
angular.element(document.body).injector().get('$cordovaPush').onNotification
Thanks to this ionic forum entry
please update your ng-cordova.js in lib/ng-cordova.js from http://ngcordova.com/docs/install/ in ng-cordova-master\dist\ng-cordova.js

Categories

Resources