NSUsernotification response returns nil sometimes - android

I am creating an application where I am reflecting my Android notifications on mac and reply to them from mac itself. I am using NSUsernotification to do the same. Notifications work perfectly. When I click on reply button and type in text, sometimes notification.response returns nil in didActive notification delegate. Can anyone help me with that?
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
if notification.activationType == NSUserNotification.ActivationType.replied {
print(notification.response) //This is nil sometimes. Not always
}
}

Related

Cancel notification recieved from FireBase client side Android/IOS?

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

FCM push notification to reawaken app not effective while device slept

I ran into a problem with my flutter app where when it's minimized or the phone is put to sleep for too long (~5+ minutes), the app stops listening to firestore changes. One solution that I came across was to send push notifications to reawaken the device. While it seems to have fixed minimizing problem (the app now responds to changes), however it still suffers from the sleep problem. I noticed that the app still receives the push notifications, but the screen doesn't light up upon receiving them. Could that be why? Is there something that I can do to force the app to connect to the internet? I'm trying to think of a solution like sending a data payload to change the data locally, but I'm not sure if that's the optimal approach (or if it would even work). I'll post my firebase cloud function for sending messages on a doc update:
exports.sendLobbyNotificationTest = functions.firestore
.document("Lobbies/{lobbyCode}")
.onUpdate((change) => {
console.log("Checking for need of push notification...");
// const oldValue = change.before.data() || {};
const newValue = change.after.data() || {};
if (newValue.pushNotification == true) {
console.log("Found a push notification request for: ",
newValue.lobbyCode, "!");
// Set lobby back to false
admin.firestore().collection("Lobbies")
.doc(newValue.lobbyCode).update({
pushNotification: false,
});
return admin.messaging().sendToTopic(newValue.lobbyCode, message)
.then((result) => {
console.log("Message sent successfully: ", result);
// usersRef.where("lobbyCode", "==", newValue.lobbyCode).get()
// .then(function(querySnapshot) {
// querySnapshot.forEach(function(doc){
// })
// })
}).catch((err) => {
console.error("Error sending message: ", err);
});
}
console.log("No message needs to be sent!");
// return dummy value to prevent error
return 0;
});
const message = {
notification: {
title: "Bzzzt!",
body: "You've been buzzed!",
},
};
Is there something I'm missing?
Update: I think it just doesn't work because the phone is locked, once unlocked it begins to function normally.
I think figured out why from reading here: https://developer.android.com/training/monitoring-device-state/doze-standby.html (I had trouble finding this).
Basically if I use the right priority settings for android and ios (priority & content_available) it will bring the app out of idle and listen for changes.

Android Notifications not display the message body

I am writing my own message provider to send out push notifications on both iOS and Android. I have the provider working well for iOS. My problem is Android. With the app not running, The phone gets the message and notifies the user a message came in. I only see the icon in the message. The message body is not displayed. If the app is running, the app gets the message event and I can see in the JSON, the message body and message title. So it would appear that the information is coming through. I've tried this on an Android running JellyBean and Marshmallow and get the same results. I also tried using Googles test notification from their web site for FCM. I get the same results with their web notification send. Any ideas?
Here is the code I am using in Delphi:
HttpClient.Request.URL := 'https://fcm.googleapis.com/fcm/send';
HttpClient.Request.ContentType := 'application/json';
HttpClient.Request.CustomHeaders.Add('Authorization: key = ***'); // Server Key from Google
HttpClient.Request.CharSet := 'utf-8';
JSONMsg := TJSONObject.Create;
JSONMsg.AddPair('to', devicetoken);
JSONInfo := TJSONObject.Create;
JSONInfo.AddPair('body', edtMessage.Text);
JSONInfo.AddPair('title', 'CODY Mobility');
JSONInfo.AddPair('priority', 'high');
JSONTrue := TJsonTrue.Create;
JSONFalse := TJsonFalse.Create;
JSONInfo.AddPair('content_available', JSONTrue);
JSONInfo.AddPair('dry_run', JSONFalse);
JSONToSend := TStringStream.Create(JSONMsg.ToString, TEncoding.UTF8);
StatusMemo.Lines.Add('Sending Android message to device: ' + deviceToken);
try
HttpClient.Post('https://fcm.googleapis.com/fcm/send', JSONToSend);
except
on E:Exception do begin
StatusMemo.Lines.Add('Message send failed: ' + E.Message);
end;
end;
StatusMemo.Lines.Add('Android message response: ' + HttpClient.ResponseText);
FreeAndNil(JSONTrue);
FreeAndNil(JSONFalse);
I have found my problem! It appears to be a bug with Delphi. My original message sent was:
{"to":<MyDeviceID>","notification":{"body":"It finally works!!!!!","title":"CODY Mobility Title","priority":"high","content_available":false,"dry_run":false}}
If I change my message to the following, it now works:
{"to":"<MyDeviceID>","data":{"message":"It finally works!!!!!","title":"CODY Mobility Title","priority":"high","content_available":false,"dry_run":false}}
I had to change from "notification" to "Data" and I had to change the "body" element to a "message" element. With those changes in place, the phone gets and displays the message when the app is closed. Of course, this no longer matches Google's specs for sending a notification with Firebase Cloud Messaging. I dug into the Delphi code and I found a Delphi java script called NotificationPublisher.Java. In there, there is code which specifically looks for a message element.
if (jsonVal != null) {
if (jsonVal.has("message"))
{ msg = jsonVal.optString("message"); }
else if (jsonVal.has("msg"))
{ msg = jsonVal.optString("msg"); }
else if (jsonVal.has("alert"))
{ msg = jsonVal.optString("alert"); }
if (jsonVal.has("title"))
{ title = jsonVal.optString("title"); }
}
} else {
// Look for msg or message in bundle
if (key.equals("message"))
{ msg = valstr; } else if (key.equals("msg")) { msg = valstr; }
if (key.equals("title"))
{ title = valstr; }
}
I am not sure where Delphi checks for Notification elements versus Data elements. But I believe this is part of the problem. I created a support ticket so Embarcadero can look into this further. If anyone else has this problem... Just change your message and it'll work.

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)

Error with PushPlugin when the App is in background

I'm trying to implement a push notification app created with Cordava 3.3 using this: https://github.com/phonegap-build/PushPlugin ; Basing me in this tutorial: www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql
But I have 2 basic problems the first is that the notification does not lead if the app is in background or is closed and the second is that the message reaches Undefined when the app is open in the foreground, could help, as far as I was reading may be due the format of the JSON response or parameters sent in the same.
Here is my code not take long:
https://github.com/jedidas/Push
I achieved a solution that is on file with the plugin "GCMIntentService.java" near line 80 is the next instruction
else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
discover you can change the "price" for what you want, for example change the "price" for "message" and everything was solved milagorsamente, explain:
we have this:
. 1 $ message = array ("deprive" => $ message);
and read when I read it as:
1. E.payload.message
gives us comes as undefined because payload.price.
In this sense, we have to file in the JAVA plugin
if (extras.getString ("message")! = null && extras.getString ("message"). length ()! = 0) {
                     createNotification (context, options);
                 }
if that does not run because it is coming as "price" instead of "message". everything is solved when I change the "price" of SEND_MESSAGE.PHP for "message." thus not even need to modify the JAVA.

Categories

Resources