Cancel notification recieved from FireBase client side Android/IOS? - android

Is it possible to cancel a pushed notification before displaying it on the users phone ?
I have some custom logic which decides whether a notification needs to be displayed/appear . Is it possible for me to control this behaviour from the client side ios/android code ?

Once a message is sent to Firebase Cloud Message, there is no way to cancel its delivery.
If your message contains only a data element and no notification, displaying the message is handled by your application code - so in that case you may be able to suppress its display there.

Although the best way is to handle this is to cancel it on backend side, you still can add UNNotificationServiceExtension and override the didReceive method:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) {
self.receivedRequest = request;
self.contentHandler = contentHandler
self.content = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let content = self.content {
// I had to check something inside the push itself
if let infoDictionary = content.userInfo {
// Check something inside the push notification
contentHandler(content)
return
}
}
// Otherwise, send an empty notification to the system and it will show nothing
contentHandler(UNNotificationContent())
}

Related

flutter firebase messaging handling clicked notification on background

I'm using the firebase_messaging package on my flutter app and it works perfectly for everything except that when the app on the background and I get a notification it only opens the app and never do what I ask it does after opening the app ..here is my code:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
final dynamic data = message.data;
print("data is $data");
if(data.containsKey('request_id')) {
print("we are inside ..!");
RegExp exp = RegExp(r'\d+');
var id = int.parse(exp.firstMatch(data['request_id']!)!.group(0)!);
OpenRequestsController openRequestsController = Get.isRegistered<OpenRequestsController>()?Get.find():Get.put(OpenRequestsController());
OpenRequest matchingRequest = openRequestsController.openRequestsList.firstWhere((request) => request.id == id);
print("the request from the list is $matchingRequest");
openRequestsController.openRequestDetails(matchingRequest,false);
}
}
what happens here is that it tries to run the whole function when the message is received not when clicked .. and ofc it fails because the app is not already running in the foreground
For opening the application and moving to the said screen you need to implement onMessageOpenedApp in the initstate of your first stateful widget which will let the application to know that it is supposed to open the application when a notification being clicked. The code function should look like this:
FirebaseMessaging.onMessageOpenedApp.listen((message) {
Get.to(() => const MainScreen()); // add logic here
});
It is better if you could assign identifiers for the type of screens you want to open on clicking a particular notification while sending the notification and implement an if-else or switch statement here on the basis of message type.
Thanks

Problems with implementing OneSignal Corna SDK

I am trying to implement OneSignal Corna SDK for receiving PUSH NOTIFICATIONS,
But it is giving me a runtime error
stack traceback:
/Users/ojussave/Library/Application Support/Corona/Simulator/Plugins/plugin_OneSignal.lua:49: in function 'Init'
main.lua:52: in main chunk
This error means that there was likely a syntax error in your code. Make sure you have formatted the call to the OneSignal init method correctly, like so:
-- This function gets called when the user opens a notification or one is received when the app is open and active.
-- Change the code below to fit your apps needs.
function DidReceiveRemoteNotification(message, additionalData, isActive)
if (additionalData) then
if (additionalData.discount) then
native.showAlert( "Discount!", message, { "OK" } )
-- Take user to your app store
elseif (additionalData.actionSelected) then -- Interactive notification button pressed
native.showAlert("Button Pressed!", "ButtonID:" .. additionalData.actionSelected, { "OK"} )
end
else
native.showAlert("OneSignal Message", message, { "OK" } )
end
end
local OneSignal = require("plugin.OneSignal")
-- Uncomment SetLogLevel to debug issues.
-- OneSignal.SetLogLevel(4, 4)
OneSignal.Init("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "############", DidReceiveRemoteNotification)

How to get Registration ID with Intel XDK?

For a while now, I have been trying to figure out how to send push notifications. The app I have made is for Android right now, but I want to extend it to other devices once I figure this out. I've looked into various services, such as Amazon SNS, but they all neglect to include how to get the device token. They all assume you know how to do that.
So what I am asking is: how do I get a device token/registration ID for a device?
I tried using this code:
var tokenID = "";
document.addEventListener("deviceready", function(){
//Unregister the previous token because it might have become invalid. Unregister everytime app is started.
window.plugins.pushNotification.unregister(successHandler, errorHandler);
if(intel.xdk.device.platform == "Android")
{
//register the user and get token
window.plugins.pushNotification.register(
successHandler,
errorHandler,
{
//senderID is the project ID
"senderID":"",
//callback function that is executed when phone recieves a notification for this app
"ecb":"onNotification"
});
}
else if(intel.xdk.device.platform == "iOS")
{
//register the user and get token
window.plugins.pushNotification.register(
tokenHandler,
errorHandler,
{
//allow application to change badge number
"badge":"true",
//allow application to play notification sound
"sound":"true",
//register callback
"alert":"true",
//callback function name
"ecb":"onNotificationAPN"
});
}
}, false);
//app given permission to receive and display push messages in Android.
function successHandler (result) {
alert('result = ' + result);
}
//app denied permission to receive and display push messages in Android.
function errorHandler (error) {
alert('error = ' + error);
}
//App given permission to receive and display push messages in iOS
function tokenHandler (result) {
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('device token = ' + result);
tokenID = result;
}
//fired when token is generated, message is received or an error occured.
function onNotification(e)
{
switch( e.event )
{
//app is registered to receive notification
case 'registered':
if(e.regid.length > 0)
{
// Your Android push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('registration id = '+e.regid);
tokenID = e.regid;
}
break;
case 'message':
//Do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
}
//callback fired when notification received in iOS
function onNotificationAPN (event)
{
if ( event.alert )
{
//do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert(event.alert);
}
if ( event.sound )
{
//play notification sound. Ignore when app is in foreground.
var snd = new Media(event.sound);
snd.play();
}
if ( event.badge )
{
//change app icon badge number. If app is in foreground ignore it.
window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
}
All I get is an alert that says "result = ok". The alerts later on in the code don't happen. I've tried making sense of the code but I'm not getting anywhere. Any suggestions? Is there a tutorial for this I'm not finding?
Those legacy intel.xdk functions are being retired (the will continue to live in an 01.org, see the notice on this page: https://software.intel.com/en-us/node/492826).
I recommend you investigate one of the many push notification Cordova plugins that are available. Use your favorite web search tool to search for something like "cordova phonegap push notification plugin" to find some. The good ones will have examples of how to use.
Note:-
Unregister - Its not strictly necessary to call it.....
Ensure that you have a sender ID for Android (no idea about iOS).
Result OK means that the plugin is installed correctly and has run properly.
Problems could be due to:
Incorrect sender ID
Testing in emulator without adequate setup
Important - Push notifications are intended for real devices. They are not tested for WP8 Emulator. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator, however doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator".
onNotification must be available as a global object. So try attaching it to the window. Refer to this question
Examples of properly initializing PushPlugin in:
Ionic (my answer)

Pushwoosh get Additional data - Custom data

I'm using Pushwoosh to send notification both under Android and iOS.
Now it's possible to send Custom data under the Additional data tab of the Send push web page.
So I put some like this
{"event" : "1234"}
on the Custom data field but I can't get this kind of data on the app.
This is what I get under Android
{
"title":"test 4",
"collapse_key":"do_not_collapse",
"from":"320152062216",
"onStart":true,
"foreground":false,
"p":"f"
}
This is what I get under iOS
{
aps = {
alert = "test 4";
sound = default;
};
p = f;
}
Is there anyone who has managed to make it work?
Thanks.
I think Stack might be not the best place for this, but custom data is available only on Premium accounts.

Events and callbacks firing incorrectly in pushwoosh push notifications

I'm using the plugin's registerDevice and unregisterDevice methods and looking at my app's control panel in pushwoosh. My app's preference defaults to accepting push notifications, so I register, that works and my subscriber count increments in pushwoosh control panel. It also fires a push-notification event where the event has the notification property as the guide shows, but it's set to null. This is confusing as I have not yet sent any push notifications from the control panel.
I then set my push preference to false and unregister the the device. It works because my subscriber count decrements in the control panel, but the fail callback is the one that fires, and the only argument it gets is the same push token string that the register success callback got. If I unregister again after that, still only the fail callback fires but this time the only argument is the empty string.
Am I doing something wrong with handling responses from the plugin?
The code I'm testing with:
(function() {
$document.on('push-notification', function(evt) {
var n = evt.originalEvent.notification;
console.log(n);
});
var pushPrefApply = function() {
app.pushPref(function(pushPref) {
console.log('pushPref', pushPref);
if (!pushPref) {
window.plugins.pushNotification.unregisterDevice(
function() {
console.log('unreg ok', arguments);
},
function() {
console.log('unreg fail', arguments);
}
);
return;
}
window.plugins.pushNotification.registerDevice(
{
projectid: '123456789012',
appid : 'F0000-BAAAA'
},
function(pushToken) {
console.log('reg ok', arguments);
},
function(status) {
console.log('reg fail', arguments);
}
);
});
};
//code for changing/initiating push preference goes here
})();
$document is not a typo, it's defined already. app.pushPref is the preference setting/fetching function. window.plugins.pushNotification.onDeviceReady has been done elsewhere on deviceready.
I'm hoping the pushwoosh devs will shed some light on this.
The problem has been fixed and SDK has been updated on Github:
https://github.com/shaders/push-notifications-sdk
and
https://github.com/shaders/phonegap-cordova-push-notifications
Also Android Phonegap sample now includes unregister function:
https://github.com/shaders/push-notifications-sdk/tree/master/SDK%20Sample%20Projects/Android-Phonegap

Categories

Resources