Cannot receive FCM (Push Notification iOS) - 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.

Related

Flutter ios appstore validateReceipt on non-consumable in-app purchase

I seem to be stuck on this. Trying to validate the receipt (server side) on an in-app purchase on IOS (haven't tried with android, yet.)
I'm using the official in_app_purchase pub package.
This is the setup to initialize the purchase:
Future<bool> initiatePurchase() async {
...
(verify store is available)
..
print ("==> Store available, initiating purchase");
final PurchaseParam purchaseParam =
PurchaseParam(productDetails: _productDetails![0]);
await InAppPurchase.instance.buyNonConsumable(purchaseParam: purchaseParam);
return true;
}
Here's my verify purchase call:
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
PurchaseVerifRest purchaseRest = PurchaseVerifRest();
Map<String,dynamic> rsp = await purchaseRest.verifyPurchase(
{
"source": purchaseDetails.verificationData.source,
"vfdata": purchaseDetails.verificationData.serverVerificationData
});
// bundle up the source and verificationData in a map and send to rest
// call
return rsp['status'] == 200;
}
On the server side, the code looks like this (NodeJS/express app)
// (in router.post() call - 'purchaseData' is the map sent in the above code,
// the 'vfdata' member is the 'serverVerificationData'
//. in the 'purchaseDetails' object)
if (purchaseData.source == ('app_store')) {
const IOS_SHARED_SECRET = process.env...;
let postData = {
'receipt-data': purchaseData['vfdata'],
'password': IOS_SHARED_SECRET
};
try {
let verif_rsp = await execPost(postData);
retStatus = verif_rsp.statusCode;
msg = verif_rsp.data;
} catch (e) {
retStatus = e.statusCode;
}
}
What I get back, invariably is
210003 - Receipt could not be authenticated
... even though the purchase seems to go through, whether I validate or not.
Details/questions:
Testing with a sandbox account.
This is for a 'non-consumable' product purchase.
I'm assuming that purchaseDetails.verificationData.serverVerificationData is the payload containing the receipt to send to Apple for verification. Is this not correct? Is there another step I need to do to get the receipt data?
I've read in other posts that the verification step is only for recurring subscriptions and not for other types of products. Is this correct? I don't see anything in Apple's docs to indicate this.
Any thoughts appreciated.

Expo - Implementing Notifications Set App Icon Badge Number

Despite numerous attempts to implement the app icon badge number in our Expo app, the app icon badge number could not be set. The documentation on setting notifications app icon badge number is also very limited. We are trying to set app icon badge number to 1 when there is new push notification and then reset the app icon badge number to 0 after the user clicked on the notification.
Can anyone point out what’s wrong here?
The following is the callback function for the Notifications listener.
handleNotification = async (notification) => {
const { origin, data, notificationId } = notification
const notif = { id: notificationId, ...data }
// set notifications badge count
try {
const setAppBadgeCount = await Notifications.setBadgeNumberAsync(1)
console.log(`showing app badge number to 1 ${setAppBadgeCount}`)
} catch (err) {
console.log('did not manage to show notif app badge count!', err)
}
if (origin === 'selected') {
this.navigateToNotificationScreen(data)
try {
const resetAppBadgeCount = await Notifications.setBadgeNumberAsync(0)
console.log(`reset app badge count ${resetAppBadgeCount}`)
} catch (err) {
console.log('did not manage to reset notif app badge count!', err)
}
} else { // origin === 'received', show in-app
const { dispatch } = this.props
dispatch(setActiveNotifications([notif]))
setTimeout(() => {
dispatch(setInactiveNotifications([notif]))
}, 10000)
}
}
Thanks in advance!
Ah I got reminded that I didn't leave my solution here. In my case, the Expo front end code was written perfectly. The way I wrote it above works like a charm. Issue for me is that the backend request sent to the Expo server wasn't written correctly. Refer to this link - https://docs.expo.io/versions/latest/guides/push-notifications/#sending-notifications-from-your-server
[
{
"to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
"sound": "default",
"body": "Hello world!"
},
{
"to": "ExponentPushToken[yyyyyyyyyyyyyyyyyyyyyy]",
"badge": 1,
"body": "You've got mail"
},
{
"to": [
"ExponentPushToken[zzzzzzzzzzzzzzzzzzzzzz]",
"ExponentPushToken[aaaaaaaaaaaaaaaaaaaaaa]"
],
"body": "Breaking news!"
}
]
Specifically, I didnt add the param "badge": 1 in the request body of the notification sent to the Expo server. As a result, the app icon badge number is not set at all.

Firebase Cloud functions - collapsible IOS notifications

I use cloud functions to send notifications. It works, but I want collapsible messages. How can I do it? Here is my current function:
exports.sendNotifications = functions.database
.ref("/users/{userId}/data")
.onWrite(event => {
const userId = event.params.userId;
if (!event.data.val()) {
return;
}
const payload = {
notification: {
title: `Hey`,
body: 'It's your turn!'
//icon: receiver.photoURL
}
};
const options = {
collapseKey: 'myturnkey'
};
return admin
.database()
.ref(`users\/${userId}\/data\/notificationkey`)
.once('value')
.then(data => {
console.log('inside key', data.val());
if (data.val()) {
return admin.messaging().sendToDevice(data.val(), payload, options);
}
});
});
I tried "collapseKey" and "collapse_key" in options but none of them works, I still receive notifications every time my function is called, so I get a list of notifications on my iphone whereas I want only one.
EDIT
I also tried the parameter "apns-collapse-id" according to the FCM messages documentation, but when when I try to deploy the functions the console says " apns-collapse-id: 'myturnkey', ^ SyntaxError: Unexpected token -"
Thank you,
Alexandre
You can do this, or manipulate current notifications in other ways, using the registration.getNotifications() API which gives you access to all the currently visible notifications for your web app.
But you need to write this code in your Service-worker
see this documention for merging-notifications

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

FCM token get refreshed after some time

I have developed an iOS App using Xamarin and integrated FCM (Firebase Cloud Messaging) for push notifications. Its working fine on development phase, but on beta testing through test flight, the FCM token automatically regenerates or refreshes after some time (in between 5-10 minutes).
void TokenRefreshNotification(object sender, NSNotificationEventArgs e)
{
// This method will be fired everytime a new token is generated, including the first
// time. So if you need to retrieve the token as soon as it is available this is where that
// should be done.
//var refreshedToken = InstanceId.SharedInstance.Token;
var token = InstanceId.SharedInstance.Token;
WriteLog("Token Refresh");
ConnectToFCM();
// TODO: If necessary send token to application server.
}
public static void ConnectToFCM()
{
Messaging.SharedInstance.Connect(error =>
{
if (InstanceId.SharedInstance.Token != null)
{
var token = InstanceId.SharedInstance.Token;
// FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
// ApnsTokenType = ApnsTokenType.Unknown;
if (!Settings.DeviceId.Equals(token))
{
Settings.DeviceId = token;
Console.WriteLine("Token Updated");
}
}
Console.WriteLine($"Token: {InstanceId.SharedInstance.Token}");
});
}
Solved.
My Observation is from same API 2 different App is installed that's causing the problem. When i uninstalled one App(which is previous one only bundle ID is different) now its working fine. No token refreshed automatically after few minutes.

Resources