IOS push notifications not being grouped - apn - ios

I am using apn push notificaitons from node server.
I want to group same nature of notifications together.
For that I am using threadId parameter but its still not grouping the notifications.
Here is my server side code:
var apnOptions = {
token: {
key: "certificates/F5TRRQ26V.p8",
keyId: "F5TRRQ26V",
teamId: "4ZGSRKDXH"
},
production: false
};
var apnProvider = new apn.Provider(apnOptions);
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
note.payload = { 'messageFrom': 'John Appleseed' };
note.topic = "com.example.myapp";
note.threadId = "870";
apnProvider.send(note, '5DA3C319EB50GDDGGAAA333DC9FE6DB240C34C66CBF1E547CD8307DCA15').then( (result) => {
console.log(result);
});
On IOS app side I am receiving this:
User Info = [AnyHashable("thread-id"): 870, AnyHashable("threadId"): 870, AnyHashable("aps"): {
alert = "\Ud83d\Udce7 \U2709 You have a new message";
badge = 3;
sound = "ping.aiff";
"thread-id" = 870;
}, AnyHashable("messageFrom"): John Appleseed]
But still the notifications are not being grouped.

Related

How to send voip push notification from node js? I can send voip push from curl but not node

I am making ios app using voip push notification.
I want to send voip push notification from node js, but not well.
I read this tutorial CallKit iOS Swift Tutorial for VoIP Apps (Super Easy) and I made ios app using voip push.
I can send voip push from curl command.
curl -v -d '{"aps":{"alert":"hello"}}' --http2 --cert chara.pem:passphase https://api.push.apple.com/3/device/ede0d5e78f771d5916345aa48bd098e86aeab40b5e7d985fb9c74586d1a5a681
node index.js
const http2 = require('http2');
const fs = require('fs');
exports.handler = async (event) => {
const bundleID = 'com.swiswiswift.CharacterAlarm'
const deviceToken = 'ede0d5e78f771d5916345aa48bd098e86aeab40b5e7d985fb9c74586d1a5a681'
const headers = {
'apns-topic': bundleID
};
const options = {
protocol: 'https:',
method: 'POST',
hostname: 'api.push.apple.com',
path: '/3/device/' + deviceToken,
headers: headers,
cert: fs.readFileSync('chara.pem'),
passphrase: "passphrase"
};
const client = http2.connect('api.push.apple.com')
const req = client.request(options)
req.setEncoding('utf8')
req.on('response', (headers, flags) => {
console.log(headers)
});
let data = ''
req.on('data', (d) => data += d)
req.on('end', () => client.destroy())
req.end()
}
exports.handler('local-test')
[Object: null prototype] {
':status': 405,
'apns-id': 'xxxxxxx-xxxx-xxxx-xxx-xxxxxxxx' }
var apn = require("apn");
var deviceToken = "device token";
var service = new apn.Provider({
cert: '.path to /cert.pem', key:'pat to ./key.pem'
});
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 60; // Expires 1 minute from now.
note.badge = 3;
note.sound = "ping.aiff";
note.alert = " You have a new message";
note.payload = {'messageFrom': 'Rahul test apn'};
note.topic = "(Bundle_id).voip";
note.priority = 10;
note.pushType = "alert";
service.send(note, deviceToken).then( (err,result) => {
if(err) return console.log(JSON.stringify(err));
return console.log(JSON.stringify(result))
});
This is a working code for apn voip push
also refer this
https://alexanderpaterson.com/posts/send-ios-push-notifications-with-a-node-backend
I'm using a slightly different approach:
If you don't know where to find or how to create the key, keyId and teamID, have a look at this article on Medium. He explains all of this in detail.
var apn = require('apn');
const { v4: uuidv4 } = require('uuid');
const options = {
token: {
key: 'APNKey.p8',
keyId: 'S83SFJIE38',
teamId: 'JF982KSD6f'
},
production: false
};
var apnProvider = new apn.Provider(options);
// Sending the voip notification
let notification = new apn.Notification();
notification.body = "Hello there!";
notification.topic = "my.bundleid.voip"; // Make sure to append .voip here!
notification.payload = {
"aps": { "content-available": 1 },
"handle": "1111111",
"callerName": "Richard Feynman",
"uuid": uuidv4()
};
apnProvider.send(notification, deviceToken).then((response) => {
console.log(response);
});

I'm getting the errorNum :8 while sending the push notifications to ios devices

var apn = require('apn');
var gcm = require('android-gcm');
export default function notification( devicetype, devicetoken, alert, userid, action, profilepic, image, youtubeimage, id ) {
if(devicetoken != "(null)") {
var androidApiKey = '', cert = '', key = '', passphrase = '';
if(process.env.NODE_ENV.toLowerCase() == "production") {
cert = '/../config/ios_support/apns-cert.pem';
key = '/../config/ios_support/apns-key.pem';
passphrase = '*****';
androidApiKey = "*******";
}
else {
cert = '/../config/ios_support/apns-dev-cert.pem';
key = '/../config/ios_support/apns-dev-key.pem';
passphrase = '*******';
androidApiKey = "********";
}
if(devicetype == "ios"){
var myDevice = new apn.Device(devicetoken);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert = alert;
note.category = "respond"
note.device = myDevice;
note.payload = { 'action': action, 'userid': userid, 'profilepic': profilepic, 'id':id};
console.log("note.payload: "+ JSON.stringify(note.payload));
//, 'WatchKit Simulator Actions': [{"title": "Show", "identifier": "showButtonAction"}]
var callback = function (errorNum, notification) {
console.log('Error is:.....', errorNum);
}
var options = {
gateway: 'gateway.push.apple.com',
//'gateway.sandbox.push.apple.com',
// this URL is different for Apple's Production Servers and changes when you go to production
errorCallback: callback,
cert: __dirname.split('src/')[0] + cert,
key: __dirname.split('src/')[0] + key,
passphrase: passphrase,
port: ****,
cacheLength: 100
}
var apnsConnection = new apn.Connection(options);
apnsConnection.sendNotification(note);
}
else if(devicetype == "android"){
var gcmObject = new gcm.AndroidGcm(androidApiKey);
var message = new gcm.Message({
registration_ids: [devicetoken],
data: {
body: alert,
action: action,
userid: userid,
profilepic: profilepic,
id: id
}
});
gcmObject.send(message, function(err, response) {
if(err) console.error("error: "+err);
// else console.log("response: "+response);
});
}
}
}
Here is my code. In console I'm getting all the stuff and device token is also fine. Android mobiles are getting notifications. But notifications are not sending to ios devices. I'm getting this error in console : Error is:...... 8.
One more thing is, for the same device I'm able to send the notification for other functionality with other code.
Really I'm pulling my hair out for this issue. And can't understand what's wrong with my code. Anyone please give solution for this.
You are using an old version. Apple has changed some thing in the push api last year in march i guess.
Also you forgot to set your topic which is mandetory for apn push Notifications
Try something like this for you if (devicetype == "ios") block
if(devicetype == "ios") {
var myDevice = new apn.Device(devicetoken);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert = alert;
note.category = "respond"
note.payload = {'action': action, 'userid': userid, 'profilepic': profilepic, 'id': id};
//you missed this one i guess
note.topic = "<your-app-bundle-id>";
console.log("note.payload: " + JSON.stringify(note.payload));
//, 'WatchKit Simulator Actions': [{"title": "Show", "identifier": "showButtonAction"}]
var callback = function(errorNum, notification) {
console.log('Error is:.....', errorNum);
}
var options = {
token: {
key: __dirname.split('src/')[0] + cert,
keyId: __dirname.split('src/')[0] + key,
teamId: "developer-team-id"
},
production: false // for development
};
var apnProvider = new apn.Provider(options);
apnProvider.send(note, myDevice).then( (result) => {
// see documentation for an explanation of result
console.log(result);
});
}
You can find the documentation here apn

Push Notifications using Firebase/Google Cloud Functions

I am trying to send a notification when a number is written to _random. I am able to get the device token, and the cloud function works perfectly. However, I do not receive the notification on the simulator. I am using the notification token that is pushed to Firebase to test with. If anybody can help, it will be highly appreciated.
https://i.stack.imgur.com/OB94c.png
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Initial function call:
exports.makeRandomFigures = functions.https.onRequest((req, res) => {
    //create database ref
    var rootRef = admin.database().ref();
    var doc_count_temp = 0;
    var keys = [];
    var random_num = 0;
    //get document count
    rootRef.once('value', (snapshot) => {
        doc_count_temp = snapshot.numChildren();
        //real number of member. if delete _timeStamp then minus 2 not 3!
        var doc_count = doc_count_temp - 3;
        //get num array previous generated
        var xRef = rootRef.child("_usedFigures");
        xRef.once('value', function(snap) {
            snap.forEach(function(item) {
                var itemVal = item.val();
                keys.push(itemVal);
            });
            //get non-duplicated random number
            var is_equal = true;
            while (is_equal) {
                random_num = Math.floor((Math.random() * doc_count) + 1);
                is_equal = keys.includes(random_num);
            }
            //insert new random vaule to _usedFigures collection
            rootRef.child('_usedFigures').push(random_num);
            rootRef.child('_random').set(random_num);
        });
    });
    //send back response
    res.redirect(200);
});
exports.sendFigureNotification = functions.database.ref('_random').onWrite(event => {
const payload = {
notification: {
title: 'Title',
body: `Test`, //use _random to get figure at index key
badge: '1',
sound: 'default'
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 * 24, //24 hours
content_available: true
};
const token = "cge0F9rUTLo:APA91bGNF3xXI-5uxrdj8BYqRPkxUPA5x9IQALtm3VEFJAdV2WQrQufNkzIclT5B671mBcvR6IDMbgSKyL7iG2jAuxRM3qR3MXhkNp1_utlXhCpE2VZqTw6Yw3d4iMMvHl1B-Cvik6NY";
console.log('Sending notifications');
return admin.messaging().sendToDevice(token, payload, options);
});
You can't get push notifications on the simulator.
To try some alternative ways check this link :
How can I test Apple Push Notification Service without an iPhone?

Push Notification to iOS successful but shows as 'failed'

I am using APN module for sending Push Notifications to iOS. It all seems to be working good but I get always 'failed' as response result after sending the message where in fact I actually get the message on the phone (so it should not be 'failed').
Why is response showing as 'failed' and how to fix it?
var apn = require('apn');
var options = {
token: {
key: "keys/AuthKey_123.p8",
keyId: "123",
teamId: "teamA"
},
production: false
};
var json_message = {
"aps" : {
"alert" : {
"title" : "This is title",
"body" : "This is body",
}
};
var apnProvider = new apn.Provider(options);
var deviceToken = "device token";
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.sound = "ping.aiff";
note.alert = json_message.aps.alert.body;
note.payload = json_message;
note.topic = "com.test";
apnProvider.send(note, deviceToken).then( (result) => {
console.log(result);
console.log("\n*** Response: ***\n");
console.log(JSON.stringify(result, null, 2));
});

Sending Emoji in Push Notifications via Node js on iOS

I am using apn module to send push to ios. It is working fine. But now I want to send emojis in push notifications.
var apns = require('apn');
var options = {
cert: 'abc.pem',
certData: null,
key: 'abc.pem',
keyData: null,
passphrase: 'xyz',
ca: null,
pfx: null,
pfxData: null,
gateway: 'gateway.push.apple.com',
port: 2195,
rejectUnauthorized: true,
enhanced: true,
cacheLength: 100,
autoAdjustCache: true,
connectionTimeout: 0,
ssl: true
}
var message=req.body.post; // if I give a static value like message=\ud83d, it works fine
var deviceToken = new apns.Device(iosDeviceToken);
var apnsConnection = new apns.Connection(options);
var note = new apns.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600;
note.badge = 1;
note.sound = 'ping.aiff';
note.alert = message;
apnsConnection.pushNotification(note, deviceToken);
If I send what comes from form field, I see \ud83d in the phone. If I send \ud83d from server, I see Emoji on the phone. What to do to get emojis on phone by getting it from form.
Use iOS emoji codes.
Example: For victory hand emoji in node js:
notification.alert = 'This is a test notification \u270C';

Resources