titanium appcelerator cloudpush tray notification not showing - titanium

Iam developing an application that uses push notifications.
Iam using ti.cloudpush module 3.2X and titanium sdk 3.2X
When i tries to recieve notification it deos not showing on tray.
I can read message inside application but it is not creating on notification tray.
here is my sample code
var CloudPush = require('ti.cloudpush');
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.showTrayNotification = true;
CloudPush.focusAppOnPush = false;
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
CloudPush.addEventListener('callback', function(evt) {
alert(evt.payload);
//alert(JSON.stringify(evt.payload));
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
});
Thanks in advance

Assuming you have set up the PushNotifications.subscribe correctly the default properties of this module are used until you set a property for the first time.
Because the properties are persisted to the device settings (via Titanium.App.Properties), the most recent value you set will always be used.
Do a Build > Clean to make sure you have not overwritten one of these properties by accident.
Then double check what they are set to with quick logging check -
Ti.API.log(Ti.App.Properties.getString('oneofthecloudproperties');
You should then be able to see if it's an issue with the subscribe event or how you have set the push notification properties.

Related

Scheduled Push Notification action onClick/onPress event in react native push notification?

I'm using this package for implementing local push notification:
https://github.com/zo0r/react-native-push-notification
I'm using action button like this to show buttons in my notification along with a text and a title:
PushNotification.localNotification({
...
actions: '["Yes", "No"]'
})
I wanted to know how I can call a function when user clicks on of these actions and app becomes visible?
I've tried PushNotification.configure in my componentDidMount method in my home screen like this but nothing comes up in the console:
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
if (notification.userInteraction) {
console.log("NOTIFICATION:");
}
// process the notification
}
});
I got it working.
In your App.js you need to set popInitialNotification to true. Something like this:
async componentDidMount() {
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification.action);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
}
notification.action will gibe you the label of the button clicked.
In your button/app active event you forgot to call to schedule the notification and actually set when it will arise, so you need to
PushNotification.localNotificationSchedule(details: Object)
Schedule it for now with the same id, then your notification will come up immediately.
See all options for scheduling here
import PushNotificationAndroid from 'react-native-push-notification'
(function() {
// Register all the valid actions for notifications here and add the action handler for each action
PushNotificationAndroid.registerNotificationActions(['Accept','Reject','Yes','No']);
DeviceEventEmitter.addListener('notificationActionReceived', function(action){
console.log ('Notification action received: ' + action);
const info = JSON.parse(action.dataJSON);
if (info.action == 'Accept') {
// Do work pertaining to Accept action here
} else if (info.action == 'Reject') {
// Do work pertaining to Reject action here
}
// Add all the required actions handlers
});
})();
DO NOT USE .configure() INSIDE A COMPONENT, EVEN App
If you do, notification handlers will not fire, because they are not loaded. Instead, use .configure() in the app's first file, usually index.js.
It's mentioned in the documentation.
Try to follow their example for implementation It will help you to setup in your project.

Is it possible to log a firebase event inside Headless js?

I'm trying to log a firebase event when a user is receiving a remote push notification when the app is in the background/killed. My notification displays juste fine but I can't log analytics events.
I have tried initializing my firebase app with firebase.initializeApp(config), not knowing if it was initialized in a headless js task but it didn't seem to make a difference.
In-app events log just fine using the Debug View in the firebase console, as well as the notification_receive one automatically
export default async (message: RemoteMessage) => {
const localNotification = new firebase.notifications.Notification()
// setting notification props
const displayNotification = await firebase.notifications().displayNotification(localNotification);
firebase.analytics().logEvent('notification_test', { test: 'test123' }); // this doesn't work
return Promise.resolve(displayNotification);
};
Is there a way to log an event here?
Also, any information on how Headless js works (besides official doc that I've already read of course) would be appreciated.
Thank you!

Outlook Web App add in Dialog Api messageParent not working

I am developing a Outlook add in and was checking out the authentication flow (Microsoft login) for my app. I tried using the dialog api to achieve this but was not able to pass message from the dialog to the task pane after successful sign in.
index.js:
var fullUrl = 'https://localhost:3000/src/templates/auth.html'
Office.context.ui.displayDialogAsync(fullUrl,
{height: 40, width: 40}, function (result) {
console.log("Dialog has initialized. Wiring up events");
_dlg = result.value;
console.log(result.status);
_dlg.addEventHandler(Office.EventType.DialogMessageReceived, function(responseMessage){ console.log(responseMessage);});
});
Dialog box:
Office.initialize = function (reason) {
$(document).ready(function () {
Office.context.ui.messageParent("Message 1");
}
}
In the dialog console I get this,
outlook-web-16.01.debug.js:4587 Failed to execute 'postMessage' on
'DOMWindow': The target origin provided ('https://outlook.live.com')
does not match the recipient window's origin
('https://localhost:3000').
Any idea what could be the problem?

Service Worker - Wait for clients.openWindow to complete before postMessage

I am using service worker to handle background notifications. When I receive a message, I'm creating a new Notification using self.registration.showNotification(title, { icon, body }). I'm watching for the click event on the notification using self.addEventListener('notificationclick', ()=>{}). On click I'm checking to see if any WindowClient is open, if it is, I'm getting one of those window clients and calling postMessage on it to send the data from the notification to the app to allow the app to process the notification. Incase there is no open window I'm calling openWindow and once that completes I'm sending the data to that window using postMessage.
event.waitUntil(
clients.matchAll({ type: 'window' }).then((windows) => {
if (windows.length > 0) {
const window = windows[0];
window.postMessage(_data);
window.focus();
return;
}
return clients.openWindow(this.origin).then((window) => {
window.postMessage(_data);
return;
});
})
);
The issue I am facing is that the postMessage call inside the openWindow is never delivered. I'm guessing this is because the postMessage call on the WindowClient happens before the page has finished loading, so the eventListener is not registered to listen for that message yet? Is that right?
How do I open a new window from the service worker and postMessage to that new window.
I stumble this issue as well, using timeout is anti pattern and also might cause delay larger then the 10 seconds limit of chrome that could fail.
what I did was checking if I need to open a new client window.
If I didn't find any match in the clients array - which this is the bottle neck, you need to wait until the page is loaded, and this can take time and postMessage will just not work.
For that case I created in the service worker a simple global object that is being populated in that specific case for example:
const messages = {};
....
// we need to open new window
messages[randomId] = pushData.message; // save the message from the push notification
await clients.openWindow(urlToOpen + '#push=' + randomId);
....
In the page that is loaded, in my case React app, I wait that my component is mounted, then I run a function that check if the URL includes a '#push=XXX' hash, extracting the random ID, then messaging back to the service worker to send us the message.
...
if (self.location.hash.contains('#push=')) {
if ('serviceWorker' in navigator && 'Notification' in window && Notification.permission === 'granted') {
const randomId = self.locaiton.hash.split('=')[1];
const swInstance = await navigator.serviceWorker.ready;
if (swInstance) {
swInstance.active.postMessage({type: 'getPushMessage', id: randomId});
}
// TODO: change URL to be without the `#push=` hash ..
}
Then finally in the service worker we add a message event listener:
self.addEventListener('message', function handler(event) {
if (event.data.type === 'getPushMessage') {
if (event.data.id && messages[event.data.id]) {
// FINALLY post message will work since page is loaded
event.source.postMessage({
type: 'clipboard',
msg: messages[event.data.id],
});
delete messages[event.data.id];
}
}
});
messages our "global" is not persistent which is good, since we just need this when the service worker is "awaken" when a push notification arrives.
The presented code is pseudo code, to point is to explain the idea, which worked for me.
clients.openWindow(event.data.url).then(function(windowClient) {
// do something with the windowClient.
});
I encountered the same problem. My error was that I registered event handler on the window. But it should be registered on service worker like this:
// next line doesn't work
window.addEventListener("message", event => { /* handler */ });
// this one works
navigator.serviceWorker.addEventListener('message', event => { /* handler */ });
See examples at these pages:
https://developer.mozilla.org/en-US/docs/Web/API/Clients
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage
UPD: to clarify, this code goes into the freshly opened window. Checked in Chromium v.66.

Push notification with Appcelerator (ACS) on Android

I'm trying to implement push notification with Appcelerator Cloud Service on Android But I have some issues ... tiapp.xml here :
<sdk-version>2.0.2.GA</sdk-version>
<modules>
<module platform="commonjs" version="2.0.5">ti.cloud</module>
<module platform="android" version="2.0.5">ti.cloudpush</module>
</modules>
Android runtime v8 and ti.cloudpush included, here is my app.js file
var win = Ti.UI.createWindow({
backgroundColor:'#ccc',
title:'Android Cloud Push Notification'
})
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color:'#000',
height : 53,
width : 200,
top : 100,
});
win.add(submit);
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success: function deviceTokenSuccess(e) {
alert('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken
loginDefault();
},
error: function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
});
function defaultSubscribe(){
Cloud.PushNotifications.subscribe({
channel: 'chanel',
device_token: deviceToken,
type: 'android'
}, function (e){
if (e.success) {
alert('Subscribed for Push Notification!');
}else{
alert('Error:' +((e.error && e.message) || JSON.stringify(e)));
}
});
}
function loginDefault(e){
//Create a Default User in Cloud Console, and login
Cloud.Users.login({
login: 'android',
password: 'android'
}, function (e) {
if (e.success) {
alert("login success");
defaultSubscribe();
} else {
alert('Error: ' +((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function (evt) {
//alert(evt);
alert(evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function (evt) {
//Ti.API.info('Tray Click Launched App (app was not running)');
alert('Tray Click Launched App (app was not running');
});
CloudPush.addEventListener('trayClickFocusedApp', function (evt) {
//Ti.API.info('Tray Click Focused App (app was already running)');
alert('Tray Click Focused App (app was already running)');
});
win.open();
I had the user android / android in the Appcelerator cloud console for the development mode. Launched my app to my device with debogage mode
On the app : Just click on the button "register for push notification" and see 3 alerts
1) Device Token : " all numbers "
2) login success
3) Subscribed for Push Notification!
On the Appcelerator Cloud console :
Logs -> see login & subscribe, opened it and everything's ok
Push Notifications -> 1 Android clients subscribed to push notifications. And send one throught push notifications with alert & title
And nothing appears at all ... try reboot, try to turn the app off and send another one, nothing.
I was using a device (LG OPTIMUS ONE) with android 2.2.1 with internet on it (wifi). So, I tried with another phone (SAMSUNG GALAXY S2) 3.3.2 with internet on it (wifi)
And the only change is in the cloud console :
Push Notifications -> 2 Android clients subscribed to push notifications.
But it is the same, no notification appears.
Please, I really need help for this, I succeed with iOS in 2 days and I do not understand what is the big deal here ?
I don't think I need to register with Google C2DM for using ACS.
ACS use MQTT protocol for sending push.
(I followed this step by step tut : http://www.titaniumtutorial.com/2012/06/appcelerator-cloud-push-notification-in.html)
Have you already done one project with push notification on Android & Ti ?
I checked my settings and everything is fine.
But, because I'm desperate, I also register to C2DM and nothing better, I guess I have to wait a bit more before testing.
I use the upush module in the Marketplace, took me 10 minutes to gtet it up and running, saved me loads of time.
Have you registered with Google C2DM? You need to fill out the form at https://developers.google.com/android/c2dm/signup to send notifications to the device. Make sure you have your correct App ID in the Appcelerator Cloud Settings.