Clevertap for IONIC push notification not working for IOS - push-notification

I have built an app using IONIC 1 and using clevertap for analytics and push notification. I am using an official cordova plugin to consume CLEVERTAP push notifications,
CleverTap Cordova Plugin
For android it is working fine but for IOS it is not working. Can anyone help me with this?
Here the sample initialization code,
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.addEventListener('onCleverTapProfileSync', this.onCleverTapProfileSync, false);
document.addEventListener('onCleverTapProfileDidInitialize', this.onCleverTapProfileDidInitialize, false);
document.addEventListener('onCleverTapInAppNotificationDismissed', this.onCleverTapInAppNotificationDismissed, false);
document.addEventListener('onDeepLink', this.onDeepLink, false);
document.addEventListener('onPushNotification', this.onPushNotification, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
$rootScope.CleverTap = CleverTap;
CleverTap.notifyDeviceReady();
CleverTap.registerPush();
},
onCleverTapProfileSync: function(e) {
console.log(e.updates);
},
onCleverTapProfileDidInitialize: function(e) {
console.log(e.CleverTapID);
},
onCleverTapInAppNotificationDismissed: function(e) {
console.log(e.extras);
console.log(e.actionExtras);
},
onDeepLink: function(e) {
console.log(e.deeplink);
},
onPushNotification: function(e) {
console.log(JSON.stringify(e.notification));
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
console.log('parseElement', parentElement, id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}};app.initialize();

For setting up push notifications for iOS you need to follow the steps given in the below link to setup your Apple certificates -
Setting Up Push Notifications for your app
If you plan on using deep links, check the following link -
Setting up deep links
And then from your Javascript file, use the following code to push the APNs token to CleverTap -
CleverTap.registerPush();
Let me know if this was useful to you. If you have more questions or concerns you can always reach out to CleverTap support team at support#clevertap.com

Related

Firebase sw.js not respnding after closing browser

I have created firebase project for using Cloud Messaging . until now I have sent a message from backend to client successfully when the browser (chrome) is open but when I close the browser notification not sending until reopening of the browser in below code you can see my firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "My-Sender-Id"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
self.addEventListener('push', function(e) {
var data;
if (e.data) {
data = JSON.parse(e.data.text()).data;
} else {
data = {};
}
var title = data.title;
var options = {
body: data.body,
icon: 'assets/custom/img/logo.png',
vibrate: [100, 50, 100],
requireInteraction: true,
data: data.data ? data.data : null,
dir: "rtl",
actions: [{
action: data.action,
title: 'open',
icon: 'images/checkmark.png'
},
{
action: 'close',
title: 'close',
icon: 'images/xmark.png'
},
]
};
e.waitUntil(
self.registration.showNotification(title, options)
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
if (event.action != "" && event.action != "close") {
return clients.openWindow(event.action);
}
});
how can I have notification even browser is closed?
I believe you are using service worker for FCM, and the service worker only works when the browser is open ,as service worker is responsible for handling the push notification, when the browser is closed you won't receive any push notification, Actually the push notification will appear only when the browser is opened ,or the application for which you have configured FCM is open on chrome tabs but not focused, there is one work around or you say solution for it , that is make sure the chrome browser is active in the background even after closing chrome browser.
There is option in chrome settings
Goto Settings -> Advanced -> Continue running background apps when Google Chrome is closed make sure you enable it
i have tested the code of FCM , after enabling the option you will get the notification popup.
What you are trying to achieve should be accomplished using a database like firestore. When a notification is received at the time when browser is closed, in the service worker, you should add the code to save the notification message in the firestore so that when user opens the website again, you can retrieve the messages from the firestore and can display them to user. As soon as the browser is opened, any pending notification would be saved to the database by service worker.
I believe this should be the preferred way to achieve this.

Handling multiple push notifications when restarting chrome browser

I implemented web push notifications using service worker. Now I am facing an issue. Suppose if I push 5 notifications to an endpoint(chrome browser) and assume the chrome process was not active during the push, then when I start the browser again, it is showing all the queued up notifications at once. How to prevent this scenario?
I tried with getNotifications function. But it is returning me empty notifications array. Following is my code.
self.addEventListener('push', function(event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
var data = event.data.json();
var options = {
body: data.notificationText,
icon: 'files/assets/staff.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
onClickUrl: data.onClickUrl,
event_id: data.event_id,
productName: data.product_name
}
};
event.waitUntil(
self.registration.getNotifications().then(function(notifications) {
console.log(notifications);
if (notifications && notifications.length > 0) {
notifications.forEach(function(notification) {
notification.close();
});
}
showNotification(data.title, options);
})
);
});

firebase cloud messaging: setBackgroundMessageHandler not called

I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.

From which file do I send a push notification in strongloop?

I am trying to set up push notifications with strongloop. I don't understand which file the code below lives in. The docs don't say, which is confusing for newbies.
I understand that I have to add a push component to loopback restful api application, which I have done. But how do I reference the push component from my restful api app? Where's the 'glue'?
http://docs.strongloop.com/display/public/LB/Push+notifications
var badge = 1;
app.post('/notify/:id', function (req, res, next) {
var note = new Notification({
expirationInterval: 3600, // Expires 1 hour from now.
badge: badge++,
sound: 'ping.aiff',
alert: '\uD83D\uDCE7 \u2709 ' + 'Hello',
messageFrom: 'Ray'
});
PushModel.notifyById(req.params.id, note, function(err) {
if (err) {
// let the default error handling middleware
// report the error in an appropriate way
return next(err);
}
console.log('pushing notification to %j', req.params.id);
res.send(200, 'OK');
});
});
This should live in the app.js file as seen in the example here:
https://github.com/strongloop/loopback-component-push/blob/master/example/server/app.js#L137-L145

Unregister push notifications phonegap push plugin

I have a problem with push notifications unregister. I am able to register the device and get the token, also sending notifications too, but I would like to add the unregister feature too. Here is the code y wrote for it:
var unsubscribeNotification = function unsubscribeNotification() {
try {
pushNotification.unregister(
function(e) {
//unRegister Success!!!
alert('unRegister Success');
},
function(e) {
//unRegister Failed!!!
alert('unRegister Failed');
});
}
catch(err) {
//Handle errors here
alert(err.message);
}
}
I also put a button to run the unsubscribeNotification() function when you click it. After a few seconds the application stops, no error, no messages, nothing!
I am using a Galaxy S3, I think it has Android 4.1
Thanks for the help!

Resources