I am trying to develop app with pushnotification, I am getting device token but unable to subscribe.
I am getting error i.e Required field: Channel is missing.
I did this to subscribe
var deviceToken;
var CloudPush = require('ti.cloudpush');
var Cloud = require('ti.cloud');
Cloud.PushNotifications.subscribe({
channel: 'friend_request',
type: Ti.Platform.name == 'android' ? 'gcm' : 'ios',
device_token: deviceToken
}, function (e) {
if (e.success) {
alert('Success :'+((e.message) || JSON.stringify(e)));
pushNotify();
} else {
alert('Error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
I ran into the same problem. It appears that you can't really subscribe without having a user account logged into the ACS cloud services platform.
So either create an account or use the default one. Here's a thread on Appcelerator.com solving the same problem, and with a code sample that works.
https://developer.appcelerator.com/question/135641/push-notifications-with-ticloud
Either what #Phil McCarty mentioned and make sure you are using GCM and not MQTT which has been deprecated last month. Once those settings have been done, make sure the device is sending the token of the device, as you will get this same ACS message: Channel is missing if the token is wrong.
Related
My goal is to add a biometric option to my nativescript app.
The user gets a prompt in which i'm waiting for his authentication.
if authenticated - I want to console.log("Great"). and if not log "Problem".
I'm building it using Angular + Nativescript, so I registered Fingerprint as as provider, imported it and on constructor decalred:
constructor(private fingerprintAuth: FingerprintAuth);
And for the verifyFingerPrint, when page loads I call:
this.fingerprintAuth.available()
.then((result: BiometricIDAvailableResult) => {
console.log(`Biometric ID available? ${result.any}`);
if(result.any) {
if(result.face) {
console.log("HANDLE FACE WILL BE HERE SOON!");
}
if(result.touch) {
console.log("If not face, then touch id. Let's try it.");
this.fingerprintAuth.verifyFingerprint(
{
title: "Biometric Verification",
message: "Let's just make sure it's you..."
})
.then((data) => console.log("Authenticated, contacting server now...", data))
.catch((e) => console.log("Problem occured while authenticated.", e))
}
} else {
console.log("No Biometric Option is available, try adding one.");
}
});
}
The problem is, I am getting the fingerprint prompt as expected, but after a good or bad verification I never get the console.log part. .then / .catch - both won't log anything
And i'm not getting any errors..
I'm using sidekick,
local build on a Pixel 3 XL API 28 Emulator,
Plugin name:nativescript-fingerprint-auth
Nativescript + Angular Project
What could be the problem..?
Thanks!
I just had my first contacts with the ionic framework. I've worked with Phonegap and AngularJS before however, so it was not all that new to me.
I found out that there is this new feature to use Google Cloud Messaging push notifications in Ionic, through the Ionic Push feature (http://blog.ionic.io/announcing-ionic-push-alpha/).
Related lines of code from app.js
angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
// enable push notifications
Ionic.io();
// enable users (http://docs.ionic.io/docs/user-quick-start)
// this will give you a fresh user or the previously saved 'current user'
var user = Ionic.User.current();
// if the user doesn't have an id, you'll need to give it one.
if (!user.id) {
user.id = Ionic.User.anonymousId();
// user.id = 'your-custom-user-id';
}
console.log('user-id:' + user.id);
//persist the user
user.save();
var push = new Ionic.Push({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
push.register(function(token) {
console.log("Device token:",token.token);
});
push.addTokenToUser(user);
console.log('token added to user');
});
})
Log from ionic serve
ionic $ 0 361081 log Ionic Core:, init
1 361083 log Ionic Core:, searching for cordova.js
2 361085 log Ionic Core:, attempting to mock plugins
3 361155 log user-id:1cc3d21c-b687-4988-b944-ad07b1a677c8
4 361158 log Ionic Push:, a token must be registered before you can add it to a user.
5 361159 log Ionic Push:, token is not a valid Android or iOS registration id. Cannot save to user.
6 361159 log token added to user
7 361160 log Ionic Push:, register
8 361160 error ReferenceError: PushNotification is not defined, http://localhost:8100/lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js, Line: 2
9 361526 log Ionic User:, saved user
Any input is welcome, I am also more than happy to provide more information if needed.
EDIT 10/05/2015:
found out that dev_push = false only works on physical devices, not in browser
I tried to add token to user before even registering the user
I'm having the same problem, seems not many answers online at the moment.
but even on real device, it won't save the token to user.
I just had to decide go live without push first, then use ionic deploy to follow up.
also I think you have to put this line
push.addTokenToUser(user);
inside the register callback according to this doc
http://docs.ionic.io/docs/push-usage
You also need to declare 'ionic.service.push' as a dependency in your angular module if you'd like to use it.
angular.module('starter', ['ionic','ionic.service.core', 'ionic.service.push'])
I have it like this and it works:
Ionic.io();
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
// save our newly created user
user.save();
}
var push = new Ionic.Push({});
push.register(function (token) {
console.log("Got Token:", token.token);
// now we have token, so add it to user
push.addTokenToUser(user);
// don't forget to save user to Ionic Platform with our new token
user.save();
});
// set this user as current, so we can acess him later
Ionic.User.current(user);
Did you use this
ionic config set dev_push true-if testing in emulator or laptop
ionic config set dev_pushfalse - if testing on the phone
ionic push --google-api-key Your API Key
ionic config set gcm_key Project Number
Your token is the registration id that is unique for a particular device. That is sent to you by android.
Your Phone (With the API Key)---------> to Google's GCM
Google GCM (recognises it's you via your Project number and API key) -----> Oh it's you let me make a note of it. (Save a token id in it's DB and send's one to you.)
You get a registration id unique for your device(will change if an app is uninstalled).
You call your server say hey it's me your user. Please Notify me if you get something.
Server obliges, says, okay dude, I got this. Saves the registration id with your details probably your username in it's DB.
Now from Server.
I need to inform my users about a great deal(or an accident or something).
Pull up all targeted registration Id's from DB(maybe on some condition)
registrationIds.push(regId) //in a loop
and sender.send(message, registration, function(err, result){
});
Send to Google. Google see's oh only these many people(not all maybe) from this API Key need a notification. no Problem I will notify them and you receive a notification, my dear friend.
As mentioned in the link , Adding token to the $ionicUser is done by doing , user.addPushToken(pushToken); .
For this to work you should first configure the app not to use developement pushes by ,
ionic config set dev_push true
After initialising Ionic.io and Ionic.push , load the user or create one with a new random id ,
Ionic.io();
var push = new Ionic.Push();
Ionic.User.load(localStorage.id).then(function (user) {
Ionic.User.current(user);
pushFactory.register(push, user);
}, function (error) {
/*the user with that id is not present , so create one with a random id and register the push */
});
The push factory is defined as below,
function pushFactory() {
return {
'register': function (push, user) {
push.register(function (pushToken) {
user.addPushToken(pushToken);
user.save().then(function (answer) {
console.log('user saved'+answer);
})
})
}
}
}
I don't have any more hair to tear out and need help..
I want to send messages to a topic (or channel) from a server (via GCM) so it reaches all devices subscribing to that topic.
Sending push messages to individual devices works fine and the format for sending to topics is the same, except for specifying a deviceToken, specify the topic in the for /topics/mytopic
This is described here:
https://developers.google.com/cloud-messaging/downstream
https://developers.google.com/cloud-messaging/topic-messaging
On the Titanium side (Android for now but the plan is IOS too later on) I register the device to a channel "myChannel". I can verify this by a success message returned and also in Appcelerators console.
Now, I simulate a server with curl, and send a message to "myChannel" to GCM. The message response with success and I receive back a message_id from GCM.
curl -H "Content-Type:application/json" -H "Authorization:key=APIKEY" --data '{"to": "/topics/myChannel","data": {"payload":{ "message": "Hi!" } }}' https://gcm-http.googleapis.com/gcm/send
My problem is that this message is not routed to the device.
I am guessing there is some syntax conversion needed between the channel subscribed to in Titanium and the one I use to GCM but I don't know.
The funny thing is, as soon I put in the deviceToken in curl it works perfectly.
Am I missing something fundamental here? Is the channel not there to route the same message to multiple devices subscribing to it?
Any help, clues are much appreciated.
My code looks like this:
// Require the module
var CloudPush = require('ti.cloudpush');
// Initialize the module
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
CloudPush.addEventListener('callback', receivePush);
function receivePush(evt) {
alert("Notification received: " + JSON.stringify(evt.payload));
}
function deviceTokenSuccess(e) {
Alloy.Globals.DeviceToken = e.deviceToken;
Titanium.API.info(Alloy.Globals.DeviceToken);
// Subscribe to topic
var Cloud = require("ti.cloud");
var subscribe_data = {
device_token: Alloy.Globals.DeviceToken,
channel: Alloy.Globals.topicChannelID,
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
};
Cloud.PushNotifications.subscribeToken(
subscribe_data, function (e) {
if (e.success) {
Titanium.API.info('Subscribed successfully');
} else {
Titanium.API.error('Error subscribing');
}
});
}
// Something went wrong getting the device token
function deviceTokenError(e) {
Titanium.API.error('Failed ' + e.error);
}
GCM doesn't know about channels. That's something Arrow tracks and translates to the subscribed tokens. So you need to send push via the Arrow API or Appcelerator Dashboard.
http://docs.appcelerator.com/platform/latest/#!/guide/Sending_and_Scheduling_Push_Notifications
http://docs.appcelerator.com/arrowdb/latest/#!/api/PushNotifications
For a while now, I have been trying to figure out how to send push notifications. The app I have made is for Android right now, but I want to extend it to other devices once I figure this out. I've looked into various services, such as Amazon SNS, but they all neglect to include how to get the device token. They all assume you know how to do that.
So what I am asking is: how do I get a device token/registration ID for a device?
I tried using this code:
var tokenID = "";
document.addEventListener("deviceready", function(){
//Unregister the previous token because it might have become invalid. Unregister everytime app is started.
window.plugins.pushNotification.unregister(successHandler, errorHandler);
if(intel.xdk.device.platform == "Android")
{
//register the user and get token
window.plugins.pushNotification.register(
successHandler,
errorHandler,
{
//senderID is the project ID
"senderID":"",
//callback function that is executed when phone recieves a notification for this app
"ecb":"onNotification"
});
}
else if(intel.xdk.device.platform == "iOS")
{
//register the user and get token
window.plugins.pushNotification.register(
tokenHandler,
errorHandler,
{
//allow application to change badge number
"badge":"true",
//allow application to play notification sound
"sound":"true",
//register callback
"alert":"true",
//callback function name
"ecb":"onNotificationAPN"
});
}
}, false);
//app given permission to receive and display push messages in Android.
function successHandler (result) {
alert('result = ' + result);
}
//app denied permission to receive and display push messages in Android.
function errorHandler (error) {
alert('error = ' + error);
}
//App given permission to receive and display push messages in iOS
function tokenHandler (result) {
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('device token = ' + result);
tokenID = result;
}
//fired when token is generated, message is received or an error occured.
function onNotification(e)
{
switch( e.event )
{
//app is registered to receive notification
case 'registered':
if(e.regid.length > 0)
{
// Your Android push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('registration id = '+e.regid);
tokenID = e.regid;
}
break;
case 'message':
//Do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
}
//callback fired when notification received in iOS
function onNotificationAPN (event)
{
if ( event.alert )
{
//do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert(event.alert);
}
if ( event.sound )
{
//play notification sound. Ignore when app is in foreground.
var snd = new Media(event.sound);
snd.play();
}
if ( event.badge )
{
//change app icon badge number. If app is in foreground ignore it.
window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
}
All I get is an alert that says "result = ok". The alerts later on in the code don't happen. I've tried making sense of the code but I'm not getting anywhere. Any suggestions? Is there a tutorial for this I'm not finding?
Those legacy intel.xdk functions are being retired (the will continue to live in an 01.org, see the notice on this page: https://software.intel.com/en-us/node/492826).
I recommend you investigate one of the many push notification Cordova plugins that are available. Use your favorite web search tool to search for something like "cordova phonegap push notification plugin" to find some. The good ones will have examples of how to use.
Note:-
Unregister - Its not strictly necessary to call it.....
Ensure that you have a sender ID for Android (no idea about iOS).
Result OK means that the plugin is installed correctly and has run properly.
Problems could be due to:
Incorrect sender ID
Testing in emulator without adequate setup
Important - Push notifications are intended for real devices. They are not tested for WP8 Emulator. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator, however doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator".
onNotification must be available as a global object. So try attaching it to the window. Refer to this question
Examples of properly initializing PushPlugin in:
Ionic (my answer)
I'm trying to send push notifications to my Android device from my server. Using plug PushNotification Cordova, my code is something.
var androidConfig = {
"senderID": "inspired-berm-101218",
};
document.addEventListener("deviceready", function(){
$cordovaPush.register(androidConfig).then(function(result) {
// Success
}, function(err) {
// Error
})
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
sessionService.set("token_device",notification.regid);
My information according to me, I followed advice from this forum and tutorials are good and are these:
Api KEY : AIzaSyDtZndyGvmWXF0TpYe83KVDgxRZ4MR3zK8
ID del proyecto: inspired-berm-101218
NĂºmero del proyecto: 805573676421
All this I use both my application and server are the same codes, but nevertheless, I receive the error:
{"multicast_id":7843752850335107662,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
Try uninstalling the application on my phone and reinstall but nothing, does not this work for me.
Use this website to create and run the application again immediately, it gives the exact data.
Google Developers