badge should be set before opening the app in IOS - ios

When notification received on IOS device at that time the badge should be changed and Badge should be set before opening the app.
I check this onNotificationOpen() method. But when I tap on notification then it calls.
I use cordova-plugin-firebase.
Here is the link https://github.com/arnesson/cordova-plugin-firebase
But is there a method that calls when the notification received on IOS device?
$ionicPlatform.ready(function() {
if (typeof FirebasePlugin != 'undefined') {
window.FirebasePlugin.subscribe("notficationsubscribe");
// Below method calls when i tap on notifcation and sets the badge number
window.FirebasePlugin.onNotificationOpen(function(data) {
window.FirebasePlugin.setBadgeNumber(4);
}
}
}
Above FirebasePlugin.onNotificationOpen() method calls when I tap on notification and sets the badge number, but I want to set the badge when notification received.
Anyone have ideas? How can I achieve it?

Actually i set a logic for it.
1) I stored a badgeCounter value to database.
2) when i wants to send the notification at that time i retrieve it from database
var badge = badgeCounter // it is an integer value
var notification = {
'title': 'Stock available',
'body': 'Click here to more details...',
'sound': 'default',
'badge': badge
};
3) After tap or click on notification, i cleared the badge using below.
window.FirebasePlugin.setBadgeNumber(0);
4) And also in database i update the value to '0' (zero).
Thus, i solve it and it perfectly works for me.

You don't set this with code, it will set itself based on what your notification contains. You'll have to include "badge":1 (or whatever number) in the notification payload when you send it from your server (Firebase). I'm not sure how it works with firebase, but take a look at the documentation for remote notifications. Notice the "Badge"-key.

Related

IOS Push Notification count

I need to display push notification count. when user launches the application by tapping application or from notification bar.
Example: application is in background and device received 10 notifications related to my app. we have to display notification count 10 within app.
I can achieve this by adding content-update key in notification payload. But I don't want to make change in notification payload.
Your backend need to send bagdes for this :- Eaxmple
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
and you can use this badges in your apps.
You can check how many notifications were received (assuming you are incrementing badges in your push notifications) by checking [UIApplication sharedApplication].applicationIconBadgeNumber.
This also assumed you reset the badge count each time they leave the app (standard practice), if for some reason you don't though, simply save [via NSUserDefaults] the current badge count in the willResignActive callback and check the delta when they return.

iOS: Do something when a UserNotification is received?

Is it possible to do something when the UserNotification message is delivered to the user every time?
let tdate = Date(timeIntervalSinceNow: 10)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: tdate)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let identifier = "hk.edu.polyu.addiction.test"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if error != nil {
debugPrint("center.add(request, withCompletionHandler: { (error)")
} else {
debugPrint("no error?! at request added place")
}
})
This is the code i did to deliver a notification when the user press a button. (i.e., after 10s, the notification appear to the user.)
Even the user not press on the notification, i want some variable of the app updated (assume the app is at the background).
Possible?
Or, as long as this notification is done. another new notification is scheduled, according to some calculations in my app, possible? (not fixed time, cannot use repeat)
Yes, it is possible! Need to modify the capabilities :
Enable background fetch in background mode.
Enable remote notification in background mode.
Implement delegate method : application:didReceiveRemoteNotification:fetchCompletionHandler:
This delegate method gets called when the notification arrives on the phone, so you can refresh your data.
When user taps on notification delegate method: didReceiveRemoteNotification
gets called and opens the app and user will get latest data in the app.
Apple API reference:
If your payload is not configured properly, the notification might be
displayed to the user instead of being delivered to your app in the
background. In your payload, make sure the following conditions are
true:
The payload’s aps dictionary must include the content-available key
with a value of 1. The payload’s aps dictionary must not contain the
alert, sound, or badge keys. When a silent notification is delivered
to the user’s device, iOS wakes up your app in the background and
gives it up to 30 seconds to run.

Is there anyway to save push notifications?

When user a sends a push notification to user b, user b will receive the notification, but once they click on it the payload from that notification is gone. Instead when user b opens the notification, the payload in the notification will get saved to parse, so he can view all the notifications that were sent to him. It's like a notification history. Below is my code to send notifications. I need help on how to save the payload within those notifications, so users can look at notification history.
func pushNotifications(){
let userQuery: PFQuery = PFUser.query()!
userQuery.whereKey("objectId", containedIn: Array(setOfSelectedFriends))
let pushQuery: PFQuery = PFInstallation.query()!
pushQuery.whereKey("user", matchesQuery: userQuery)
let push = PFPush()
push.setQuery(pushQuery)
push.setMessage("\(username!) wants you to meet them at \(location!)")
push.sendPushInBackgroundWithBlock {
success, error in
if success {
print("The push succeeded.")
} else {
print("The push failed.")
}
}
}
You probably should do it the other way around, make a table where you save new "MeetingInvites" and whenever a new entry gets added send a push notification to the corresponding user.
Make the push notification a side effect of the actual new entry. Not make the entry a side effect of the push notification.
That would also save you the trouble of having to deal with notifications that get lost - maybe the receiving user opens the app, then something crashes and your push notification and all the connected data would be lost.
A little bit more detail: Create a column for the location, one column for the "requesting" user and one for the "partner". In your code, set the currentUser as the requesting one, and the partner as the ... well ... partner. Then either on your client device or on the server create a push message. In both cases send the push message to the "partner".

iOS push notification not received when screen is locked

I am using parse for push notification. Once I receive remote notification I pass it to the local notification, but issue is when screen is locked didReceiveRemoteNotification does not hit. I don't receive any notification.
I am using iOS8
Here's my payload:
{
CommentId = "8082a532-2380-4af5-bb3f-d247cfca519b";
CommentTitle = test; action = "com.lelafe.one4communities.Notifications.NotificationActivity";
aps = { };
moduleIdentifier = 8;
nTitle = "Comment posted by someone";
postingID = "c57a3d27-cfe5-41e9-a311-98a9fd7749ad";
}
There is one more parameter that you need to pass to your payload i.e. content-available and set its value to 1. It needs to be passed in case we wish that our app should receive notifications in the background.
The official documentation of parse describes this parameter as follows:
+content-available: (iOS only) If you are a writing a Newsstand app, or an app using the Remote Notification Background Mode introduced in iOS7 (a.k.a. "Background Push"), set this value to 1 to trigger a background download.
The problem is your dictionary aps:
Try checking out Apple's Documentation about The Notification Payload
Also Quoting #mamills answer:
If there is no badge, no alert, and no sound specified in the
dictionary (for the "aps" key) then a default message will not appear
and it will be completely silent.
Look again at example 5 in the document you referenced. aps can be
empty, and you can specify whatever custom data you would like as they
do with the "acme2" key. The "acme2" data is an example of where your
server's "special" payload could reside within the JSON payload.

is it possible to send a push notification without using the alert attribute in a json using iOS?

I am trying to send a json format which doesn't have an "alert" attribute. The thing is, when I try to remove the alert attribute, the notification won't appear. Is there any way I can handle this? Thanks in advance
P.S I've tried to use action, however it still doesn't show up (I think this is only possible in android)
Yes, you can do it. It is possible to send a push notification without an alert. You can even register your application just to badge notifications, in which case the provider server won't even be able to send alerts or sounds.
The Notification Payload
Each push notification carries with it a payload. The payload specifies how users are to be alerted to the data waiting to be downloaded to the client application. The maximum size allowed for a notification payload is 256 bytes; Apple Push Notification Service refuses any notification that exceeds this limit. Remember that delivery of notifications is “best effort” and is not guaranteed.
For each notification, providers must compose a JSON dictionary object that strictly adheres to RFC 4627. This dictionary must contain another dictionary identified by the key aps. The aps dictionary contains one or more properties that specify the following actions:
An alert message to display to the user
A number to badge the application icon with
A sound to play
Note that it says one or more of the properties. The alert property is optional. You can even send a notification with an empty aps dictionary (i.e. send only custom properties).
The following example shows an empty aps dictionary; because the badge property is missing, any current badge number shown on the application icon is removed. The acme2 custom property is an array of two integers.
{
"aps" : {
},
"acme2" : [ 5, 8 ]
}
The only alert the user will see it the alert that asks him/her whether to allow push notifications. That alert will only be displayed the first time the app is launched after installation.
In the below example you register to non alert notifications (badges and sounds only) :
Registering for remote notifications
- (void)applicationDidFinishLaunching:(UIApplication *)app {
// other setup tasks here....
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
[self sendProviderDeviceToken:devTokenBytes]; // custom method
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
Hope this will help you.

Resources