I’m trying to develop Firebase - Push Notifications with Framework7. I have installed the plugin by checking $ cordova plugin list
cordova-plugin-fcm 2.1.2 “FCMPlugin”
I have registered the app on the Firebase Console and have no idea whether this code is correct or not (it’s inside the app.js)
onDeviceReady: function() {
// JScript for the main app, once PGap has loaded.
//checkDeviceSize(); (WILL RE-CODE IN A CSS FRIENDLY FORMAT)
document.addEventListener(“offline”, onOffline, false);
document.addEventListener(“online”, onOnline, false);
setTimeout(function() {
navigator.splashscreen.hide();
}, 1000);
var pushtoken;
initFCM();
getToken();
},
then, at the bottom of file app.js, I put the function
function initFCM() {
console.log("initializing...");
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.onTokenRefresh(function(token){
pushtoken = token;
app.dialog.alert('onTokenRefresh:', token);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
FCMPlugin.onNotification(function(data){
if(data.wasTapped){
app.dialog.alert(JSON.stringify(data));
}else{
app.dialog.alert(JSON.stringify(data));
}
}, function(msg){
app.dialog.alert('onNotification callback successfully registered: ' + msg);
}, function(err){
app.dialog.alert('Error registering onNotification callback: ' + err);
});
}
}
function getToken() {
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.getToken(function(token){
pushtoken = token;
app.dialog.alert('getToken:', token);
if (!token) setTimeout(getToken, 1000);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
}
}
Would be very grateful if you can show how to manage this code inside app.js
Many thanks
Related
I want to be able to send push notifications using Titanium and Arrow Push on Android.
I have followed the instructions here:
Configuring Push Services
Subscribing to push notifications
Modules.CloudPush
My simple code looks as follows:
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
// Works fine
CloudPush.retrieveDeviceToken({
success: function () {
deviceToken = e.deviceToken;
alert('deviceToken: ' + deviceToken);
subscribeToChannel();
},
error: function () {
alert('Failed to register for push notifications! ' + e.error);
}
});
// Never runs!!!
CloudPush.addEventListener('callback', function (evt) {
Ti.API.info('New notification!');
alert("Notification received: " + evt.payload);
});
// Works fine
function subscribeToChannel () {
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'general',
type: Ti.Platform.name
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
Most of the above code is similar to the docs. The subscription aspect of the code seems to works perfectly fine, as the user's device also appears in the devices section of the Appcelerator Dashboard.
However when it comes to sending a notification, from the Appcelerator Dashboard, the word "Failure" appears next to my Android device.
The full error message when highlighting the "?" icon is as follows:
Exception Type: GCM; Error Code: 3103; Error Message:
RegistrationId(s) is null or empty; Catched Exception: argument cannot
be null
I looked this error up on http://docs.appcelerator.com/arrowdb/latest/#!/guide/troubleshooting and all it says is:
The GCM client provided a null or empty registration ID. This error is
uncommon if you are using the Modules.CloudPush module.
Which isn't helpful.
What am I doing wrong? Is this a bug on Accelerator side.
Turns out my code was fine. The credentials I was using however was incorrect. Please see my other related question here:
Appcelerator/ Titanium: Getting Android credentials to push notifications
The docs are in need of updating.
I'm hardly an expert with push, but I compared what you have to what I have in one of my apps.
Pretty sure you need to send the deviceToken into the subscribeToChannel function.
Try changing this -
function subscribeToChannel () {
to this -
function subscribeToChannel (deviceToken) {
then add the token to the call here -
subscribeToChannel (deviceToken);
Let me know if that works for you.
-Jon
On subscribeToChannel() function, you should use type : 'gcm' instead of type: Ti.Platform.name
This is a commonJS module that I created for my Android push:
function ACSPush(_callback) {
var debug_mode = true;
var Cloud = require('ti.cloud');
var CloudPush = require('ti.cloudpush');
CloudPush.enabled = true;
var deviceToken;
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
if(debug_mode)
Ti.API.info('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
if(Ti.App.Properties.getString("deviceToken") != deviceToken.toString()){
defaultSubscribe();
};
},
error : function deviceTokenError(e) {
if(debug_mode)
Ti.API.info('deviceTokenError.. :( ' + e.error);
}
});
function defaultSubscribe() {
Cloud.PushNotifications.subscribeToken({
channel : 'MyChannel',
device_token : deviceToken,
type : 'gcm'
}, function(e) {
if(e.success) {
if(debug_mode)
Ti.API.info("Success registerForPushNotifications");
Ti.App.Properties.setString("deviceToken", deviceToken.toString());
} else {
if(debug_mode)
Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
};
});
};
CloudPush.addEventListener('callback', function(evt) {
var payload = JSON.parse(evt.payload);
if(debug_mode){
Ti.API.info("Received a push notification\nPayload:\n" + JSON.stringify(evt.payload));
Ti.API.info("payload: " + payload);
};
_callback(payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Focused App (app was already running)');
});
};
module.exports = ACSPush;
Obviously, you must first configure Android Push Service http://docs.appcelerator.com/platform/latest/#!/guide/Configuring_push_services-section-src-37551713_Configuringpushservices-ConfiguringpushservicesforAndroiddevices
I am using cordova plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXX
this plugin. And added following code into javascript file.
function setupPush() {
var push = PushNotification.init({
"android": {
"senderID": "XXXXXXXX"
},
"ios": {
"sound": true,
"alert": true,
"badge": true
},
"windows": {}
});
push.on('registration', function(data) {
console.log("registration event: " + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
}
It gives error as "TypeError: Cannot call method 'init' of undefined".
This usually happens if you haven't done this after onDeviceReady. You can't access any native device APIs until after this fires (push notifications, camera, etc).
function onDeviceReady() {
// Sets up your push notifications
setupPush();
}
// Fires when device is ready.
document.addEventListener("deviceready", onDeviceReady, false);
I have received push notification using FCM plugin. when i m clicking on notifiation, app splash screen was open but i but open another screen. how can i do it? please help.
app.js
.run(function ($ionicPlatform, $rootScope, $state) {
$ionicPlatform.ready(function() {
if(window.cordova) {
FCMPlugin.onNotification(
function(data){
$rootScope.notificationData = data;
$rootScope.reciveMessage(data);
$state.reload();
if(data.wasTapped){
// $state.go('message', {id:data.pageId});
// $location.path('app/userList');
console.log('onNotification tapped true');
} else {
console.log("xxxxxxxxxxxx"+data.message);
}
},
function(msg){
// alert("asdf"+msg)
console.log('onNotification callback successfully registered: ' + msg);
FCMPlugin.getToken(
function(token){
//alert(token);
window.localStorage.setItem("deviceId",token)
},
function(err){
console.log('error retrieving token: ' + err);
}
)
},
function(err){
// alert("fjkjg"+err)
console.log('Error registering onNotification callback: ' + err);
}
);
}
});
})
I am trying to implement Firbase push notification using cordova. I use the code for the latest fcm plug in specificaion from here : Cordova Push Plugin
I can get the register token. Then I tried to send notification from Firebase test notification module using that token. Each time I run the app in my device I am having the alert-
"Msg: onNotification callback successfully registered: OK"
it is inside the second function of FCMPlugin.onNotification event.
But the first function [where I want to get the notification] is not called.
I don't find where I am making mistake. Here is my code inside onDeviceReady:
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
var parentElement = document.getElementById('deviceready');
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
//=========================
FCMPlugin.getToken(
function (token) {
alert("Token: " + token);
cordova.plugins.email.open({
to: 'sharif#nascenia.com',
subject: 'Greetings',
body: token
});
},
function (err) {
alert("Error: " + 'error retrieving token: ' + err);
}
);
FCMPlugin.onNotification(
function (data) {
alert("Notify: " + JSON.stringify(data));
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert("Wrapped Notify: " + JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert("Notify: " + JSON.stringify(data));
}
},
function (msg) {
alert("Msg: " + 'onNotification callback successfully registered: ' + msg.Notification);
},
function (err) {
alert("Error: " + 'Error registering onNotification callback: ' + err);
}
);
};
Make sure you add "click_action":"FCM_PLUGIN_ACTIVITY" to the payload for the REST API. This must be present for Android. If this isn't available you will NOT receive data from a tapped notification (or hear a sound).
See the REST API payload example from the cordova-plugin-fcm documentation:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY", // <<<<<<< Must be present for Android
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"/topics/topicExample",
"priority":"high",
"restricted_package_name":""
}
You are missing to subscribe to your topic before onNotification function like this :
FCMPlugin.subscribeToTopic('topic');
I need to make a push notification listener, My code for this is below and it runs perfect till the subscription and the dashboard confirms it is subscribed successfully, but the problem occurs with the receiver.
Alloy.Globals.ServiceAddress = "my service address";
Ti.API.info("1");
var CloudPush = require('ti.cloudpush');
var Cloud = require("ti.cloud");
var deviceToken = null;
loginUser(); // flow starts from here
function loginUser() {
Cloud.Users.login({
login: 'User',
password: 'Password'
}, function(e) {
if (e.success) {
var user = e.users[0];
// alert("Loggin successfully");
getDeviceToken();
} else {
alert("Error2*** :" + e.message);
//Ti.API.info('error ')
}
});
}
function getDeviceToken() {
if (Ti.Platform.Android) {
CloudPush.debug = true;
CloudPush.focusAppOnPush = false;
CloudPush.enabled = true;
CloudPush.showAppOnTrayClick = true;
CloudPush.showTrayNotification = true;
CloudPush.singleCallback = true;
CloudPush.singleCallback = true;
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
}
}
// Enable push notifications for this device
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
alert(e.deviceToken);
subscribeToChannel(deviceToken);
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Process incoming push notifications
function subscribeToChannel(deviceToken) {
// Subscribes the device to the 'news_alerts' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'Vision', //'You_App',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function(e) {
if (e.success) {
alert('Subscribed');
SendNotification(deviceToken);
} else {
// indicator.visible = false;
alert('Subscribe Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function SendNotification(to_deviceToken) {
alert('sendnot');
Cloud.PushNotifications.notifyTokens({
channel: 'My Cannel',
to_tokens: to_deviceToken,
payload: 'Welcome to push notifications'
}, function(e) {
if (e.success) {
alert('Success Send');
} else {
alert('Send Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}
When I add event-listener to push notifications it doesn't even fire up however, the client is saying it is connected.
<!-- language: lang-js -->
CloudPush.addEventListener('callback', function (evt) {
alert('rec');
alert("Notification received: " + 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)');
});
PS. I have searched and already read related threads Like this one
I am attaching the log to make it clarify that subscription and notification send is working properly
Push notification Log
and
Connected Clients
Solved
I was compiling with titanium api level 4.1.1.v20151203143424 with CloudPush module version 3.2.1
I migrated to titanium 6.0.0.v20160202173231 with cloudpush module version 3.4.1
and all set see in this pic