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.
Related
I have a requirement to aggregate remote notifications of the same type.
example:
if a user received a push notification saying:"user 1 commented on your post", and then received "user 2 commented on your post", when receiving the second push I should remove the first notification and create a custom notification saying "2 users have commented on your post".
I'm getting the counter in the userInfo dictionary and I'm using NotificationService Extension in order to modify the notification's content.
the problem is I'm presenting 2 notifications:
"user 1 commented on your post"
"user 3 and 2 others have commented on your post"
instead of only the 2nd notification.
I've tried initializing UNNotificationRequest with custom identifier but still I'm getting double notifications (the original one and then the custom one).
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["push.comment"])
if let username = bestAttemptContent.userInfo["sender"] as? String,
let count = bestAttemptContent.userInfo["views_counter"] as? Int {
bestAttemptContent.title = "\(username) and \(count) others have commented on your post"
}
bestAttemptContent.body = "tap to see"
let request = UNNotificationRequest(identifier: "push.comment", content: bestAttemptContent, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
I tried using available-content : 1 in the notification's payload, but I'm not able to modify the notification when the app is terminated (not in background/foreground).
Basically I want a similar behaviour to facebook's messenger app.
Any Suggestions?
Push Notifications grouping is a feature that is provided in Android applications, but it is impossible to achieve the same on iOS. Because it should be handled by operation system(in other case it will be not possible to achieve when app is closed or minimized) and iOS doesn't provide this support.
So I read in Apple's documentation that when setting content-available : 1 in the aps object it launches the app in a background mode and its possible to handle the received silent push.
its important to avoid setting the mutable-content : 1 and add background modes with remote notifications on in the apps configurations.
I have a big problem, I set up (with great difficulty) push notifications on my iOS project. I decided to receive the data of the notification in the "didReceiveRemoteNotification" method of the "AppDelegate" then to create it programmatically (in order to carry out mandatory personal treatment). Everything works perfectly, only when I launch my application without the help of Xcode, I no longer receive the notifications, the notification creation code is not executed. I do not know what to do ...
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping
(UIBackgroundFetchResult) -> Void) {
let body = userInfo["body"]
print(userInfo)
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.body = body! as! String
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:
1, repeats: false)
let request = UNNotificationRequest(identifier: "idt", content:
content, trigger: trigger)
UNUserNotificationCenter.current().add(request,
withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
completionHandler(UIBackgroundFetchResult.newData)
}
Thanks you very much
When you launch your app from a notification you need to check the launchOptions in application:didFinishLaunchingWithOptions: to see if UIApplicationLaunchOptionsRemoteNotificationKey is present.
According to the Documentation:
The value of this key is an NSDictionary containing the payload of the remote notification. See the description of application:didReceiveRemoteNotification: for further information about handling remote notifications.
This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.
Once you determine that the launch contains a notification, invoke your notification handler method with the notification payload obtained from launchOptions.
What you have now, which is application(_:didReceiveRemoteNotification:) is only triggered when the app is already running:
If the app is running, the app calls this method to process incoming remote notifications. The userInfo dictionary contains the aps key whose value is another dictionary with the remaining notification
You need to check in your project settings/Capabilities - Background Modes - Remote notifications
Enable Remote notifications in Capabilities.
{
"aps" : {
"content-available" : 1,
"badge" : 0,
"Priority" : 10
},
"acme1" : "bar",
"acme2" : 42
}
The notification’s priority:
10 The push message is sent immediately.
The remote notification must trigger an alert, sound, or badge on the device. It is an error to use this priority for a push that contains only the content-available key.
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/BinaryProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH13-SW1
When the device is running and connected to Xcode, the system treats silent notifications as high-priority simply because the OS is smart enough to know "You must be debugging your app, so I will treat your app's tasks as high priority".
When the device is disconnected from Xcode, the system then treats silent notifications as low-priority. Therefore, it doesn't guarantee their delivery in order to improve battery life.
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.
I want add simple local notification which unclearable for particular time. like 10 minutes you can not clear it. if solution is possible through other way suggestion appreciated.
Anyone having idea about it?
what you can do is when you are dismissing all pending notification reset the particular notification again or you can remove other notifications by their identifier and keep the particular notification
here is the code to fetch all pending notifications.
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { requests in
print(requests)
for request in requests {
srrNotification.append(request)
print(request)
}
})
I've taken this code directly from Apple's page: https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent. I've place it in viewDidLoad(). UserNotifications has been imported.
It compiles, the app runs, breakpoints in the code are hit but no notification. I'm using Xcode 8 (not beta) and targeting iOS10.
Any idea what I'm doing wrong?
let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "Hello_message_body"
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 2, repeats: false)
let request = UNNotificationRequest.init(identifier: "2", content: content, trigger: trigger)
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.currentNotificationCenter()
center.addNotificationRequest(request)
Test only on the device, and check your settings like crazy. In particular:
Be sure you've asked the user for authorization. If you have no authorization, you won't get any notifications for this app. If you never saw the authorization dialog, that's the problem here.
Even if the authorization dialog appeared and you tapped Allow, there are a lot of Notification settings that can prevent your notification alert from appearing in various places.
Be sure to look in the notification center. Do Not Disturb will turn off the sound and the alert, but it will appear in the notification center unless Notification settings forbid.
Be sure to give yourself enough time after center.addNotificationRequest to get out of your app, since unless you take steps to the contrary, the notification alert will not appear when your app is frontmost. Your intervals are pretty short.