How handle silent notifications in iOS - objective-c

I need to fetch data from parse SDK and update in core data after receiving push notification(silent notification)in foreground and background.how to receive silent push notification and update data(without on click of notification).Here my code is
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
/*
//notification data format from server
{ "operation": "Update",
“Element”: “1234”,
"action": "db" }
//after receiving update notification ,i should fetch that unique element(1234) data from parse and save data into database.
*/
if ([[userInfo objectForKey:#"operation"] isEqualToString:#"Update"])
{
NSLog(#"update notication called");
//fetching data and updating database using updateDatabase method ,its implemented in some other class.
[database updateDatabase:[userInfo objectForKey:#“Element”]];
}
}
this is silent notification, So how to handle silent notification in iOS. thanks

you have to enable the background mode for that. Click on your Project Name in the file inspector, then select your target and select the tab "Capabilities". Now turn "Background Modes" on and select "Push Notifications".

Modify your payload and make sure you've content-available set to '1'. This tag is required for silent notification. Without this the payload will be a non-silent notification.
{
aps: {
content-available: 1,
sound: "default"
}
}

Related

Duplicate fcm push notification in react native android backgroundhandler

I developed react native application with rnfirebase and notifee for sending the push notification. foreground is working properly, message is displayed only once. but the background notification is displaying twice like one is from messaging().setBackgroundMessageHandler and another one is android's default push notification. First message is from default push notification and next one is from firebase messaging. So how do I remove android's default push notification. I'm also checked that first default notification is not using the firebase messaging and notifee. It's comes from outside of react native like android's native push notification
The notifications that you are seeing are most likely one from firebase and another from Notifee.
In my project I was handling the notifications that were coming from firebase via firebase.messaging().onMessage and inside this listener I was showing a local notification using Notifee so that the notification shows in the foreground.
async showNotificationInForeground(message: FirebaseMessagingTypes.RemoteMessage) {
const { messageId, notification, data } = message
const channelId = await Notifee.createChannel({
id: messageId,
name: 'Pressable Channel',
importance: AndroidImportance.HIGH,
})
await Notifee.displayNotification({
title: notification?.title || '',
body: notification?.body || '',
data,
android: {
channelId,
importance: AndroidImportance.HIGH,
pressAction: {
id: messageId,
},
smallIcon: 'ic_stat_name',
localOnly: true,
},
})
}
However what was happening was that I was calling this showNotificationInForeground method to show the local Notifee notification on both firebase's background and messaging listeners ie: firebase.messaging().onMessage and firebase.messaging().setBackgroundMessageHandler
So what I ended up doing was only calling the showNotificationInForeground method in onMessage listener and not in setBackgroundMessageHandler, which resulted in showing the local notification in the foreground, and the firebase notification in the background.
If this is not the case for you, you are most likely registering an extra notification receiver inside your AndroidManifest.xml file which is causing the duplication
I had the same problem, where there were two notifications a) 1 from notifee (which I wanted to keep) b) from FCM (which I didnt want).
Sending a data only message from my custom server solved the issue. Below is a snippet of the serverside for sending data only message :
const admin = require("firebase-admin");
// Do other stuff like create an express server to listen and trigger sending message
// Note dont forget to to initialize the app
await admin.messaging().sendToDevice(
tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: "Me",
user: "My Friend",
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: "high",
}
);
You can use other methods as well, just make sure that FCM doesnt include notification and is data only.

Scheduled Push Notification action onClick/onPress event in react native push notification?

I'm using this package for implementing local push notification:
https://github.com/zo0r/react-native-push-notification
I'm using action button like this to show buttons in my notification along with a text and a title:
PushNotification.localNotification({
...
actions: '["Yes", "No"]'
})
I wanted to know how I can call a function when user clicks on of these actions and app becomes visible?
I've tried PushNotification.configure in my componentDidMount method in my home screen like this but nothing comes up in the console:
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
if (notification.userInteraction) {
console.log("NOTIFICATION:");
}
// process the notification
}
});
I got it working.
In your App.js you need to set popInitialNotification to true. Something like this:
async componentDidMount() {
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification.action);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
}
notification.action will gibe you the label of the button clicked.
In your button/app active event you forgot to call to schedule the notification and actually set when it will arise, so you need to
PushNotification.localNotificationSchedule(details: Object)
Schedule it for now with the same id, then your notification will come up immediately.
See all options for scheduling here
import PushNotificationAndroid from 'react-native-push-notification'
(function() {
// Register all the valid actions for notifications here and add the action handler for each action
PushNotificationAndroid.registerNotificationActions(['Accept','Reject','Yes','No']);
DeviceEventEmitter.addListener('notificationActionReceived', function(action){
console.log ('Notification action received: ' + action);
const info = JSON.parse(action.dataJSON);
if (info.action == 'Accept') {
// Do work pertaining to Accept action here
} else if (info.action == 'Reject') {
// Do work pertaining to Reject action here
}
// Add all the required actions handlers
});
})();
DO NOT USE .configure() INSIDE A COMPONENT, EVEN App
If you do, notification handlers will not fire, because they are not loaded. Instead, use .configure() in the app's first file, usually index.js.
It's mentioned in the documentation.
Try to follow their example for implementation It will help you to setup in your project.

Clear Previous Expo Push Notifications

I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.
Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?
Basically I need to force an override or dismiss previous notifications.
The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.
Is there a recommended approach to this currently?
You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
// DISMISS ALL NOTIFICATION AFTER INTERACTION
Notifications.dismissAllNotificationsAsync();
});
If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.
Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
// setNotification(notification);
// DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
Notifications.dismissAllNotificationsAsync();
});
You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.
_handleNotification = (notification) => {
this.setState({notification: notification});
console.log('get notification', this.state.notification);
let localnotificationId = this.state.notification.notificationId;
setTimeout(function () {
Notifications.dismissNotificationAsync(localnotificationId);
}, 10000)
};
This is how I do in NodeJS

Xcode Recieve notification only when app is active

I write in Objective-C.
I'm using remote push up notification for app control. I don't want to disturb users with alerts and sounds when app is not active. What i need to do - if app is not active - do nothing when notification is recieved.
Thank you.
You want to send silent notifications. A notification sent without an aps key is silent. iOS will not play a sound, nor will it display a banner on the device. Your app will still receive such notifications, if it's running, and can respond as it chooses. If the app is in the background, it can display a local notification, or it can just ignore it.
Here are palyload structure which you need to receive for your case:
{
"aps" : {
"badge" : 5,
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
BTWL: you can not mention badge as well, if you don't need it.
just add below code into your Appdelegate.m file
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
UIApplicationState state = [application applicationState];
if(state == UIApplicationStateActive)
{
//app in active mode
// add your code as you want to handle
}
else{
// app is in terminated mode
}
}
It was easier than i thought. Just no alert and sound elements in array in section aps.
No alert - nothing to show.
No sound - nothing to play.

Appcelerator: Read custom variable when returning to app from push notification

So I got my first push notifications from my PHP server to the iPhone working (so excited!)
Now when the user clicks on the notification, my app reloads, but it reloads to whatever point it left off at obviously.
Is there a way I can have the app know that it was reloaded from a iOS notification click?
And the next step is to read a custom variable that I sent along with the notification, how would I read my variable? (I added the custom variable to my payload as follows:)
$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default', 'customVar' ==> '1');
Mark, You can get the custom property using the callback property of Register For Push Notifications method. Since any code written in this callback method will be invoked on receiving a remote push.
Titanium.Network.registerForPushNotifications({
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_ALERT,
Titanium.Network.NOTIFICATION_TYPE_SOUND
],
success:function(e)
{
deviceToken = e.deviceToken;
alert("deviceToken = "+deviceToken);
registerForPush();
},
error:function(e)
{
alert("Error: "+e.message);
},
callback:function(e)
{
//It'll be invoked on receiving a remote push, this e.data will contain your custom variables also
alert("push notification received"+JSON.stringify(e.data));
}
});
You can use this link for more information.