Send push notification to iOS device via Firebase (FCM) using HTTP Request after app is killed [duplicate] - ios

This question already has answers here:
Can't send push notifications using the server API
(4 answers)
Closed 6 years ago.
I am having trouble sending push notifications via Firebase through HTTP Request to my iOS device after the app is killed. When the app is in the foreground or active in the background everything work as expected. But if I kill the app it won't work. I am able to send notifications to my app through the Firebase console if the app is killed, so I believe something must be wrong with the code I am using.
This is my code for sending the push notification:
private void SendPushNotification(string devicetoken, string header, string content, string pushdescription)
{
var textNotification = new
{
to = devicetoken,
notification = new
{
title = header,
text = content,
content_available = true,
sound = "enabled",
priority = "high",
id = pushdescription,
},
project_id = "rrp-mobile",
};
var senderId = "212579566459";
var notificationJson = Newtonsoft.Json.JsonConvert.SerializeObject(textNotification);
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Authorization] = "key=AIfrSyAtgsWCMH4s_bOyj-Us4CrdsifHv-GqElg";
client.Headers["Sender"] = $"id={senderId}";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.UploadString("https://fcm.googleapis.com/fcm/send", "POST", notificationJson);
}
}
Am I forgetting something here? This works for sending push notifications to Android devices both in foreground, background and when app is killed, and like I said also to iOS devices in foreground and background.
The only issue is sending push notifications to iOS devices when the app has been killed. Does anyone have any idea as to how I would solve this issue?

I just realized my mistake, and it was very simple. I am posting this here because I believe this may be an easy thing to miss.
var textNotification = new
{
to = devicetoken,
notification = new
{
title = header,
text = content,
content_available = true,
sound = "enabled",
**priority = "high",**
id = pushdescription,
},
project_id = "rrp-mobile",
};
You need to make sure that the priority property is defined outside the "notification" scope, like this:
var textNotification = new
{
to = devicetoken,
**priority = "high",**
notification = new
{
title = header,
text = content,
content_available = true,
sound = "enabled",
id = pushdescription,
},
project_id = "rrp-mobile",
};
This will make your push notifications deliver even if the app is killed.

Related

Can't receive Firebase data messages in background Xamarin.iOS app

I have setup firebase cloud messaging in my Xamarin iOS app successfully. When I send messages via the firebase console, everything works fine.
On my backend, I added Firebase admin SDK for dotnet, and tried sending "data" messages to my iOS app in this way:
FIrst, using normal messages to topics:
var iOSMsg = new Message()
{
Topic = iOSDemoUsersTopic,
Apns = new ApnsConfig
{
Headers = new Dictionary<string, string>
{
{ "priority", "high" }
},
Aps = new Aps
{
ContentAvailable = true,
MutableContent = true
}
},
Data = notificationData.ToDictionary(kv => kv.Key, kv => kv.Value.ToString())
};
var response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
This approach didn't work. Since I receive messages only when my app is open, when it goes I close it, notifications are not received anymore.
I then decided to try old Multicast messages, hopping it will work. I did as follows:
var msg = new MulticastMessage
{
Apns = new ApnsConfig
{
Headers = new Dictionary<string, string>
{
{ "priority", "high" }
},
Aps = new Aps
{
ContentAvailable = true,
MutableContent = true,
}
},
Data = notificationData.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()),
Tokens = iOSTokens.ToList()
};
var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(msg);
But, the thing still behaves the same way.
On android, I can receive messages in background and when the app is killed when they are data messages. I have tried a million things, please can someone help ?
Finally, I found a solution.
My notifications where sent well, but when gotten by iOS, the alert object of aps was not found, so the OS couldn't display the notification.
To make this property available, the "Notification" property too should be set in the message.
var msg = new Message
{
Apns = new ApnsConfig
{
Aps = new Aps
{
ContentAvailable = true,
MutableContent = true,
}
},
Notification = new Notification
{
Body = body,
Title = title
},
Data = notificationData.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()),
Topic = iOSDemoUsersTopic
};
So, after adding the notification property, everything went fine.

iOS push notifications and Testflight using ..p8 certificate and apn

I'm trying to send Push Notifications to my ios app. They work fine for the app I download via the App store, but they don't work when I install a beta version using Testflight. This sort of defeats the purpose, as I want to test out new types of notifications and do the right thing on the app.
I think I'm doing all the right things:
Register for notifications on the app and get a device token
send the device token to my server
send the notification to the device using APNS in node.
The problem is that when I send the notification from the server to an app downloaded from Testflight, I get BadDeviceToken error. From the App Store, works perfectly.
The code in Node looks something like this:
let util = require('util');
let apn = require('apn');
class PushNotification {
constructor(production) {
production = !!production;
this.apnProvider = new apn.Provider({
token: {
key: './apns.p8', // Path to the key p8 file
keyId: 'xxxxxxxxx', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
teamId: 'YYYYYYYY' // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
},
production: production // Set to true if sending a notification to a production iOS app
});
if (production) {
process.env.NODE_ENV = "production";
}
}
sendNotificationApple(deviceToken, alert, payload, badge) {
if (deviceToken && (alert || badge)) {
let note = new apn.Notification();
note.topic = 'com.xxx.xxx';
note.expiry = Math.floor(Date.now() / 1000) + 3600 * 24 * 2; // Expires 2 days from now
if (badge != undefined && badge != -1) {
note.badge = badge;
}
note.alert = alert;
if (payload) {
note.payload = payload;
}
this.apnProvider.send(note, deviceToken).then(function (result) {
console.log(util.inspect(result, false, null));
});
}
}
}

How to prepare APN for production

Im trying to deploy my app with notifications but it's giving me the biggest headache in the world. All other questions ive seen with regards to this seem outdated.
I set up APNs to be sent from a nodeJS script that I have running. When running in my sandbox everything was working well. As soon as I sent my app to TestFlight, notifications stopped sending. My script is still Successfully sending to the Notification Id registered with my phone but im assuming its not the correct production Id. If anyone canhelp get me sending production notifications it would be greatly appreciated! Thank you
APN Server code
var options = {
token: {
key: "AuthKey_6V27D43P5R.p8",
keyId: "3Z6SEF7GE5",
teamId: "ASQJ3L7765"
},
production: true
};
var apnProvider = new apn.Provider(options);
function SendIOSNotification(token, message, sound, payload, badge){
var deviceToken = token; //phone notification id
var notification = new apn.Notification(); //prepare notif
notification.topic = 'com.GL.Greek-Life'; // Specify your iOS app's Bundle ID (accessible within the project editor)
notification.expiry = Math.floor(Date.now() / 1000) + 3600; // Set expiration to 1 hour from now (in case device is offline)
notification.badge = badge; //selected badge
notification.sound = sound; //sound is configurable
notification.alert = message; //supports emoticon codes
notification.payload = {id: payload}; // Send any extra payload data with the notification which will be accessible to your app in didReceiveRemoteNotification
apnProvider.send(notification, deviceToken).then(function(result) { //send actual notifcation
// Check the result for any failed devices
var subToken = token.substring(0, 6);
console.log("Succesfully sent message to ", subToken);
}).catch( function (error) {
console.log("Faled to send message to ", subToken);
})
}

Firebase FCM IOS don´t send Apple apns payload

I have 3 apps, 2 are working well and are receiving pushs from FCM, but one of them does not receive pushs.
I don´t know why, but my other apps receive a Push Notification like this:
{
aps = {
alert = {
body = "body here";
title = "title here;
};
badge = 3;
"content-available" = 1;
};
"gcm.message_id" = "0:1468862214187339%9c127a139c127a13";
}
But in my other app, I receive messages like this (without aps body):
{
"collapse_key" = "...";
from = 1003897668292;
notification = {
body = "body here";
e = 1;
title = "title here";
};
}
Well, so I have some questions?
I did the same process in both applications.
I use the default swizzling
I created the p12 certificate to send Push Messages and I did upload it to the Firebase Console.
Does anyone know any reason for Firebase send messages with a different format? On the server I'm sending messages in the same way.
I would like to receive messages with the "aps/alert/body" format.
kind regards

Missing topic name when "content_available" is set

we're trying to integrate GCM messaging on our iOS app. We use topic messaging to send messages to a group of devices subscribed to the same topic.
During the developemnt we noticed that enabling the "content_available" flag to let the app receive notifications while in background the message we receive is missing the topic name, so if the app is subscribed to multiple topics we're not able to determine which topic was the sender of the message.
Notification sent using HTTP api:
{
"to":"/topics/user_5",
"data":{"action":"sync","what":"user"},
"collapse_key":"866c9b6f36461511697a5089fe4b0d8e",
"delay_while_idle":true
}
Notification received on iOS:
{
action = sync;
"collapse_key" = 866c9b6f36461511697a5089fe4b0d8e;
from = "/topics/user_5";
what = user;
}
Notification sent using HTTP api, with "content_available" flag set to true:
{
"to":"/topics/user_5",
"data":{"action":"sync","what":"user"},
"collapse_key":"866c9b6f36461511697a5089fe4b0d8e",
"content_available":true,
"delay_while_idle":true
}
Notification received on iOS:
{
action = sync;
aps = {
"content-available" = 1;
};
"gcm.message_id" = "0:1436954611368845%1f9e30f91f9e30f9";
what = user;
}
Is it the expected behaviour or is it a GCM bug? Is there someone else struggling with the same thing?

Resources