I am developing a webRTC (video calling) application in ios. I am receiving a APNS push notification from server,whenever user receive a incoming video call on the device.
{
"aps" : {
"alert" : "Incoming video call from - Bob",
"badge" : 1,
"sound" : "bingbong.mp3",
"userdata" : {JSON}
}
}
How can I store it inside Local Notification?
If you want to store data in local push notification then you can add the data like this,
let interval = TimeInterval(1)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Incoming video call from - Bob"
content.body = "Your body"
content.sound = UNNotificationSound.init(named: "CustomSound.mp3")
content.badge = "Your badge number"
content.userInfo = ["userData": YOUR_USER_DATA from remote]
let req = UNNotificationRequest(identifier: "localPushNotification", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(req, withCompletionHandler: nil)
Related
Using the legacy FCM HTTPS API is it possible to send messages to a device or a device group as stated in the documentation here, but their is not information regarding sending a bath of messages via an HTTP post request, we are aware that is it possible to send batch messages using the Admin SDK
as shown here in
FCM Admin SDK
// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "5% off all electronics",
},
Token = registrationToken,
},
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "2% off all books",
},
Topic = "readers-club",
},
};
var response = await FirebaseMessaging.DefaultInstance.SendAllAsync(messages);
We are unable to confirm if it its possible to send batch messages via the HTTPS post request.
The Admin SDK wraps the FCM REST API that is documented here. From there:
HTTP request
POST https://fcm.googleapis.com/v1/{parent=projects/*}/messages:send
The URL uses gRPC Transcoding syntax.
So it looks like the REST API expects a post request.
I want to show notification counter on my app icon. I need to do it for both iOS and Android. Also counter must update when App is killed(not running) or when running in background. I am using firebase push notifications.
If I consider using common counter then I can use FirebaseMessaging.configure onMessage event to decrease the counter value, but how to increase the value of the same counter (how will I know that notification is received).
flutter_app_badger 1.1.2 description showing increasing and decreasing counter value on button press, how can I listen to notification and handle counter?
Below is my Message Payload
var tokens = [];
var payload = {
"notification": {
"title": "Contest Won! " + contestActivityFeedData.contestname,
"body": "You Have Won " + contestActivityFeedData.amount,
"click_action": "FLUTTER_NOTIFICATION_CLICK",
},
"data": {
"contestid": contestActivityFeedData.contestid,
"contestname": contestActivityFeedData.contestname,
"notificationtype": 'contest_won'
},
}
admin.messaging().sendToDevice(tokens, payload);
Any article/video/plugin for this?
You can add "badge" option to notification payload.
ref: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
const options = {
priority: 'high',
collapseKey: user_id
};
const deviceTokensPromise = db.ref('/users-fcm-tokens/' + user_id).once('value');
deviceTokensPromise.then(tokensSnapshot => {
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no device tokens to send to.');
}
const tokens = Object.keys(tokensSnapshot.val());
console.log(tokens);
console.log(payload);
return admin.messaging().sendToDevice(tokens, payload, options).then(response => {
console.log(response);
return removeInvalidFCMTokens(tokensSnapshot, response);
});
});
I have a collapse-Key field in my options.
When this code is ran, the iPhone receives multiple notifications, all on top of each other. I'd like to have most recent notification replace the previous ones.
#Timex you can pass same notification id for all notifications with the same collapse_id. For this you need to implement your own SendNotification method.
Check out the "Delivery Options" section in Firebase's FCM Messages documentation.
"collapsible" message behavior is supported on Android via FCM's collapse_key, on iOS via apns-collapse-id, and on JavaScript/Web via Topic.
Intuitively you might expect that the apns-collapse-id setting might go into the options parameter passed into the sendToMessage method you are using. However, this is not the case. Instead try patching it into the payload object, like this:
const patchedPayload = Object.assign({}, payload, {
apns: {
headers: {
'apns-collapse-id': user_id
}
}
});
This follows the payload format presented in the documentation linked above.
Once you've constructed this patched payload don't forget to update sendToDevice(tokens, payload, options) to sendToDevice(tokens, patchedPayload, options).
Hope this works out for you!
For iOS:
Use apns-collapse-id see the docs.
if you use collapsible messages, remember that FCM only allows a maximum of four different collapse keys to be used by the FCM connection server per registration token at any given time. You must not exceed this number, or it could cause unpredictable consequences.
Collapsible:
Use scenario
When there is a newer message that renders an older, related message irrelevant to the client app, FCM replaces the older message. For example: messages used to initiate a data sync from the server, or outdated notification messages.
How to send
Set the appropriate parameter in your message request:
collapseKey on Android
apns-collapse-id on iOS
Topic on Web
collapse_key in legacy protocols (all platforms)
See the implementation of apns-collapse-id in the article:
# Script to send push notifications for each song in a Phish Setlist via an updateable Push Notification.
# Place a config.yml in the same directory as the script and your push notification PEM file.
#
# Config Format:
# push_token: XXXXXXXXXXXXXX
# phish_api_key: XXXXXXXXXXXXXX
# push_mode: XXXXXXXXXXXXXX # development or production
require 'apnotic'
require 'phish_dot_net_client'
require 'awesome_print'
require 'yaml'
show_date = ARGV[0]
if show_date
script_config = YAML.load(File.read(File.expand_path('../config.yml', __FILE__)))
PhishDotNetClient.apikey = script_config["phish_api_key"]
the_show = PhishDotNetClient.shows_setlists_get :showdate => show_date
push_body = ""
if script_config["push_mode"] == "development"
connection = Apnotic::Connection.new(cert_path: "pushcert.pem", url: "https://api.development.push.apple.com:443")
else
connection = Apnotic::Connection.new(cert_path: "pushcert.pem")
end
token = script_config["push_token"]
notification = Apnotic::Notification.new(token)
notification.apns_id = SecureRandom.uuid
notification.apns_collapse_id = "Phish " + the_show[0]["showdate"] + ": "
notification.mutable_content = true
the_show[0]["setlistdata"].sets.each do |set_data|
set_name = set_data.name + ": "
set_data.songs.each do |song|
song_str = set_name + song.title
push_body = push_body + set_name + song.title + "\n"
set_name = ""
push_content = {'title' => song_str, 'body' => push_body}
puts push_content
notification.alert = push_content
response = connection.push(notification)
# read the response
puts ""
puts response.ok? # => true
puts response.status # => '200'
puts response.headers # => {":status"=>"200", "apns-id"=>"XXXX"}
puts response.body # => ""
puts ""
sleep(5)
end
end
connection.close
else
puts "Usage ruby send_push.rb SHOWDATE(Format:YYYY-MM-DD)"
end
For Android:
Use a tag variable in your notification payload.
"notification":{
"title":"Huawei",
"body":"21 Notification received",
"sound":"default",
"badge":4,
"tag":"1",
"click_action":"Your_Activity"
"icon":"Push_Icon"
}
I recommend using the latest send function from the firebase-admin, usage described here.
I have been trying to get Bosun to work with little success. Here are my problems:
1) I am able to see alerts appearing in my dashboard, but the alerts never come thru to the notification mode of my choice, be it e-mail, slack or json.
2) When I acknowledge the alerts on the dashboard, only one notification from the notification chain (first one) will be received. I.e. If I set up {email -> slack -> json}, only e-mail notification will be received, no slack and json.
Any help will be appreciated. Below is my dev.config
-------------- dev.conf ---------------
tsdbHost = qa1-sjc005-031:4242
emailFrom = bosun-alert#noreply.com
smtpHost = stmp.somedomain.com:25
checkFrequency = 1m
httpListen = :8070
# Post to an endpoint
notification json {
post = http://somedomain.com/HealthCheck/bosunAlert
body = {"text": {{.|json}}}
contentType = application/json
print = true
next = json
timeout = 5m
}
# Post to a Slack channel via Incoming Webhooks integration
notification slack {
post = https://hooks.slack.com/services/T03DNM0UU/B04QH37J6/ypn0
Uy2JwLa676soomXwItjq
body = payload={"channel": "#testing", "username": "webhookbot"
, "text" : "This is a test!"}
print = true
next = json
timeout = 5m
}
# Send out e-mail notification
notification email {
email = username#somedomain.com
print = true
next = slack
timeout = 5m
}
template test {
subject = {{.Last.Status}}: {{.Alert.Name}} on {{.Group.measurem
ent}} for {{.Group.pod}}
body = `<p>Name: {{.Alert.Name}}
<p>Tags:
<table>
{{range $k, $v := .Group}}
<tr><td>{{$k}}</td><td>{{$v}}</td></tr>
{{end}}
</table>`
}
alert test {
template = test
crit = avg(q("avg:mq1{measurement=*,pod=pod3}", "1h", ""))
warn = avg(q("avg:mq1{measurement=*,pod=pod3}", "30m", ""))
critNotification = email
warnNotification = email
}
Acknowledgements stop notification chains. So the purpose of them is really for the escalation of incidents; escalation stops when an incident has been acknowledged. As per the documentation on notifications:
notification
A notification is a chained action to perform. The chaining continues until the chain ends or the alert is acknowledged.
It seems like you might want to send to multiple notifications at the same time. To do this list them out in warnNotification and/or critNotification as appropriate:
critNotification: comma-separated list of notifications to trigger on critical.
Both the quotes are from the configuration documentation (documentation isn't that well organized currently, so I don't blame you for missing either of these)
We are trying to run the sample app for push notifications with some modification to get it to send out a broadcast notification, but it is not getting sent.
We have modified the PushBackendEmulator code as well. The emulator invokes the submitBroadCastNotification procedure successfully and the following result is returned:
Server response :: /-secure-{"result":"Notification sent to all
users","isSuccessful":true}/
However, it appears the WL.Server.sendMessage method is not sending the message and returns. I am not able to see the server side logs either after a thorough search on the liberty server except for the messages.log on the liberty server which shows the following when WL.Server.sendMessage is called.
ht.integration.js.JavaScriptIntegrationLibraryImplementation E
FWLSE0227E: Failed to send notification. Reason: FPWSE0009E: Internal
server error. No devices found [project worklight]
Here is the adapter code:
function submitBroadcastNotification( notificationText) {
var notification = {};
notification.message = {};
notification.message.alert = notificationText;
//notification.target = {};
//notification.target.tagNames = ['test'];
WL.Logger.debug("broadcast: " + notification.message.alert );
var delayTimeOut = **WL.Server.sendMessage**("PushNotificationsApp", notification);
WL.Logger.debug("Return value from WL.Server.sendMessage :"+ delayTimeOut);
return {
result : "Notification sent to all users"
};
}
Here is the PushBackendEmulator code:
public static void main(String [] args){
String serverUrl =
"http://208.124.245.78:9080/worklight";
String notificationText = "Hellofrombroadcastingnotifications";
String userId = "admin";
notificationText = notificationText.replace(" ", "%20");
Logger.debug("sending broadcast notification: " + notificationText);
URL url = new URL(serverUrl
+ "/invoke?
adapter=PushAdapter&procedure=submitBroadcastNotification¶meters=['" + userId + "','" + notificationText + "']");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.setDoOutput(true);
Logger.debug("Connected to server");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = "";
String inputLine;
while ((inputLine = in.readLine()) != null)
response+= inputLine;
Logger.debug("response is:"+ response);
in.close();
Logger.debug("Server response :: " + response);
connection.disconnect();
Looking at your application from the PMR, it seems to me like you have mixed both event source-based notifications and broadcast notifications.
If you want to use Broadcast notifications, this means you cannot try imposing sending the notification to any specific userId, etc as it is not needed nor based on userIds.
By default, all devices are auto-subscribed to a tag called "push.ALL".
You can read more about broadcast notifications API methods in the IBM Worklight Knowledge Center.
This is a modified version of your application, tested in iOS and Android: https://www.dropbox.com/s/l2yk2pbvykrzfoh/broadcastNotificationsTest.zip?dl=0
Basically, I stripped away from it anything not related to broadcast notifications:
I removed the push securitytest from application-descriptor.xml
I removed any function from the adapter XML and JS files and main.js file that is related to event source-based notifications.
The end result is that after the app is loaded, you are right inside the application (no login).
I then right-clicked the adapter folder in Studio > invoke procedure, and selected the submitBroadcastNotification option to send the notification ("aaa").
In the device, a notification was received. Tapping it (if the app is closed) launches the application, which then triggers the WL.Client.Push.onMessage API in common\js\main.js to display alerts containing the payload and props of the received notification.
This was tested in both iOS and Android.
As the application was loading, I could see in LogCat and Xcode console the token registration.
To test this in iOS, you will need to update application-descriptor.xml with your own pushSender password and add your own apns-certificatae-sandbox.p12 file.
To test in Android, make sure you are have generated a browser key in the GCM console and are using it in application-descriptor.xml
For both, make sure that all requires ports and addresses and accessible in your network