How to prepare APN for production - ios

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);
})
}

Related

Cannot receive FCM (Push Notification iOS)

I make app by React Native.
Few days ago,I was able to receive FCM. But now I cannot.
Client app permissions notification, I set Xcode(capability),firebase and Apple Developer(APNs setting).
And console.log tells me success.
But I cannot receive notification. Although few days ago I could.
Is this error in firebase??
I don't know cause, please help me m(_ _)m
=======environment==========
Xcode Version 11.3
"react-native-firebase": "^5.6.0"
"react-native": "0.61.5"
"firebase-admin": "^8.9.0"
=======addition========
Regenerating APNs and setting, I could receive notification.
But next day, I couldn't receive notification.
APNs is valid in only one day???
Most probably, in your Firebase console number of potential users are eligible for this campaign is 0 currently.
"Estimate based on approximately 0 users who are registered to receive notifications. Some targeted users will not see the message due to device inactivity. For recurring campaigns, estimate is for initial send only."
Possible solution:
1) If that's the case (0 users are registered)
--> Check if the fcmToken is received.
getFcmToken = async () => {
const fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
console.log(fcmToken);
this.showAlert(‘Your Firebase Token is:’, fcmToken);
} else {
this.showAlert(‘Failed’, ‘No token received’);
}
}
2) If the number is not zero
--> Most probably your app is opened in foreground and the notification is not displayed.
--> Try to lock your iPhone screen and the notification will appear, else try to handle it which the app is in foreground
messageListener = async () => {
this.notificationListener = firebase.notifications().onNotification((notification) => {
const { title, body } = notification;
this.showAlert(title, body);
});
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
const { title, body } = notificationOpen.notification;
this.showAlert(title, body);
});
const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
const { title, body } = notificationOpen.notification;
this.showAlert(title, body);
}
this.messageListener = firebase.messaging().onMessage((message) => {
console.log(JSON.stringify(message));
});
}
3) Check if the cert has expired (unlikely) since you mentioned that it's still working a few days back.

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));
});
}
}
}

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

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.

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

Unable to send iOS MDM Push Notification using Push Sharp

I am attempting to send the an MDM push notification to an iPad using the production APN server. However, Push Sharp says that the notification failed because the identifier is equal to 1. The following code from the PushSharp code base illustrates how it comes to that conclusion...
//We now expect apple to close the connection on us anyway, so let's try and close things
// up here as well to get a head start
//Hopefully this way we have less messages written to the stream that we have to requeue
try { stream.Close(); stream.Dispose(); }
catch { }
//Get the enhanced format response
// byte 0 is always '1', byte 1 is the status, bytes 2,3,4,5 are the identifier of the notification
var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 2));
int failedNotificationIndex = -1;
SentNotification failedNotification = null;
//Try and find the failed notification in our sent list
for (int i = 0; i < sentNotifications.Count; i++)
{
var n = sentNotifications[i];
if (n.Identifier.Equals(identifier))
{
failedNotificationIndex = i;
failedNotification = n;
break;
}
}
Basically, after the writing the payload to the stream, it attempts to close the connection, during which it expects a response from the APN service, which I think it refers to as the notification identifier.
I have plugged the device into the iPhone Device Configuration utility, but nothing appears in the console, hence I assume that it never receives this notification.
My questions are...
What is this identifier that it is expecting ?
Is there anything that I am doing wrong ?
The device is running iOS 6. The structure of the payload is as follows...
{"aps":{},"mdm":"80369651-5802-40A2-A0AE-FCCF02F99589"}
The values in the returned byte[] of 6 bytes are as follows 8,8,0,0,0,1
No idea, I've never looked into the details how PushSharp deals with the APNS internals.
You shouldn't send the "aps":{} part in the notification payload, so maybe that's the reason the APNS fails the notification.
I'm sucessfully using PushSharp 1.0.17 with the following code for MDM notifications, so it definitely works in general.
var pushService = new PushService();
// attach event listeners
// override the production/development auto-detection as it doesn't
// work for MDM certificates
var cert = null; // load your push client certificate
var channel = new ApplePushChannelSettings(true, cert, true);
pushService.StartApplePushService(channel);
// create and send the notification
var notification = NotificationFactory
.Apple()
.ForDeviceToken("your-device-token-received-from-checkin")
.WithExpiry(DateTime.UtcNow.AddDays(1))
.WithCustomItem("mdm", "your-push-magic-received-in-checkin");
pushService.QueueNotification(notification);
For PushSharp v3.0+, you should be able to include directly in the Payload of the ApnsNotification.
public void SendIosMdm(string deviceToken, string pushMagic)
{
_apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.FromObject(new {
mdm = pushMagic
})
});
}

Resources