Is it possible to trigger Notification Service Extension through Local Push Notification?
My code snippet
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
let aps = ["mutable-content": 1]
let dict = ["aps": aps, "some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
No, It is not possible to trigger notification service extension through push notification.
Reason: Service extension lets you customize the content of a remote notification before it is delivered to the user. e.g decrypt the message or download the attachments
but I personally think there is no point of downloading the notification content attachments in service extension because you can always download the attachments before scheduling. e.g
// Download attachment asynchronously
downloadAttachments(data: data) { attachments in
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Add downloaded attachment here
content.attachments = attachments
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
// No need of adding mutable content here
let dict = ["some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Let me know if you have different use case.
Pleas read the documentation before posting. The first line states:
A UNNotificationServiceExtension object provides the entry point for a Notification Service app extension, which lets you customize the content of a remote notification before it is delivered to the user.
Related
I have a local notification and the text on it could go upto 2 lines. The text shows truncated on the banner. Is it possible to word wrap the text on the notification banner without "\n"? I am not seeing any API's to do it.
Here is my code within a func which takes input params for identifier, body, trigger, userInfo, category:
let content = UNMutableNotificationContent()
content.title = "This is a very very long title text going upto 2 lines. Want to display it in word wrap."
content.subtitle = "This is subtitle text"
content.body = body
content.sound = .default
if let userInfo = userInfo {
content.userInfo = userInfo
}
if let category = category {
content.categoryIdentifier = category.identifier
}
let notification = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
log.info("Scheduling notification: id='\(identifier)', content='\(title)'")
UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in
if let error = error {
log.error("Failed to schedule local notification: \(error)")
}
})
How can we show the image or any attachment with local notifications as we used to show in rich notifications ?
I am receiving the silent notification and then changing it in local notification.
Yes, you can show it in the local notification also, you have to trigger local notification after you received silent push , I hope in your slient notification payload all require data is there.
Here is the code snippet
let content = UNMutableNotificationContent()
//Configure notification
content.title = "Notification Title"
content.body = "Notification Body"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "ImageNotification"
//Attach your image local path here (Document dir path)
let attachment = try! UNNotificationAttachment(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", url: localURL, options: [:])
content.attachments = [attachment]
content.userInfo = ["attachmentType": "Media"]
// Create a trigger for fire a local notification
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)
let request = UNNotificationRequest(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", content: content, trigger: trigger)
// Configure according to version
if #available(iOS 11.0, *) {
let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier,
actions: [],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: .customDismissAction)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([contactCategory])
} else {
// Fallback on earlier versions
let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier, actions: [], intentIdentifiers: [], options: [])
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([contactCategory])
}
UNUserNotificationCenter.current().add(request) {[weak self] (error) in
guard error == nil else {
return
}
}
After this implement it would be work fine, If you still facing any issue so please let me know.
I have an messaging app,I am using VoIP notifications to send acknowledgement to users. I am firing a local notification each time the PushKit delegate is called.
The current scenario is that the previous notification gets removed and is replaced by a newer one. Is there a way to manage local notifications such that the user can see multiple notifications in their device?
This is the code I have tried:
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Title"
notificationContent.subtitle = "Subtitle"
notificationContent.body = "Body"
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
P.S : I don't want to schedule local notification for a later period
Using for loop to register multiple Notification with the unique identifier https://developer.apple.com/documentation/usernotifications/unnotificationrequest/1649634-identifier?language=objc
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
you should change this identifier "cocoacasts_local_notification" to dynamically reset the unique identifier
let notification = UNMutableNotificationContent()
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dayComponent, repeats: true)
let lnMessageId:String = messageDict["Id"] as! String
let dayRequest = UNNotificationRequest(identifier: lnMessageId , content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(dayRequest, withCompletionHandler: {(_ error: Error?) -> Void in
if error == nil
{
//print("success")
}
else
{
//print("UNUserNotificationCenter Error : \(String(describing: error?.localizedDescription))")
}
})
Whenever app receive silent push , I am displaying the local notification.
If at the time of receiving the silent push , iPhone is locked , local notification are displaying but if application is in background and iPhone is not locked then local notification are not displaying. What could be wrong. ? I am using below code ?
let content = UNMutableNotificationContent()
content.title = "Connect"
content.body = indentificationText
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
repeats: false)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
UNUserNotificationCenter.current().delegate = appDelegate
content.userInfo = payload.dictionaryPayload
let request = UNNotificationRequest(identifier: content.title, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
NSLog("UNUserNotificationCenter Add completion Handler : \(String(describing: error?.localizedDescription))")
})
The app may be suspended in the background , so the code that creates the local notification isn't executed . . .
Background:
Im writing an application where a bot sends you messages. These messages can be received as local notification.
The Problem:
When the bot sends multiple notifications within a short span of time (1 second between each message), the notification center will only show one message. I will hear the notification sound every time I expect to, But i will still only see the first message.
Relevant code:
func postUserNotification(content: String, delay: TimeInterval, withDictionary dictionary: [String:String] = [:]) {
let notificationContent = UNMutableNotificationContent()
notificationContent.body = content
notificationContent.userInfo = dictionary
notificationContent.categoryIdentifier = "message"
let dateAfterDelay = Date(timeIntervalSinceNow: delay)
let dateComponents = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: dateAfterDelay)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let identifier = "identifier" + "\(NotificationManager.incrementor)"
let localNotification = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(localNotification){ (error : Error?) in
if let theError = error {
print("the error is \(theError.localizedDescription)")
}
}
}
Nothing wrong with your code :
Like you wrote in your question, this is mentioned in the Apple Docs:
If you are sending multiple notifications to the same device or
computer within a short period of time, the push service will send only
the last one.
https://developer.apple.com/library/content/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG23