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
Related
I need to show hyperlink in my remote notification along with Title and body. I have done some thing like this:
#IBAction func openPDFButtonPressed(_ sender: Any) {
self.scheduleNotification()
}
func scheduleNotification() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Download The Receipt"
content.body = "Kindly Download your purchase bill"
content.categoryIdentifier = "PDF"
content.userInfo = ["customData": "http://www.pdf995.com/samples/pdf.pdf"]
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponents.minute = 30
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// pull out the buried userInfo dictionary
let userInfo = response.notification.request.content.userInfo
print("Test: \(userInfo)")
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "PDFViewController") as! PDFViewController
newViewController.strURL = customData
self.present(newViewController, animated: true, completion: nil)
}
completionHandler()
}
In this I am sending url in user info but I need this url as hyperlink that shows when notification appears. and when I click on that hyperlink it will open this URL in webView.
Loading URL in webview part is done. Just need to know how can I show this url as hyperlink on notification.
kindly help me out.
You cannot control the way a notification is shown by iOS, but you can declare specific actions for your notifications. See here: https://developer.apple.com/documentation/usernotifications/declaring_your_actionable_notification_types
This lets you add your custom 'Pay, Reject, Block' actions to the notification. iOS will offer the choices to the user, and notify your app in the background when the user selects one, but you will not be able to show the URL, only text.
The only way to show a custom dialog following a notification is if you get the notification while the app is in the foreground, because then the OS doesn't show the notification, it only notifies your app, and you can then decide to show whatever UI suits you. But that kind of goes against the idea of the notification, which can come in at any time, in particular when your app is not running.
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))")
}
})
Today I am able to launch a local notification when the mobile gets into the region by using the didDetermineState just like the code bellow, even If the app is not running at all.
if (state == CLRegionState.inside){
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let content = UNMutableNotificationContent()
content.title = "Sonda"
content.subtitle = "Entrada"
content.body = "Hora: " + String(hour) + ":" + String(minutes)
content.badge = 1
content.sound = .default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let requestIdentifier = "reqIdentifier"
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
//handle error
})....
Is it possible to launch the app itself within the same method without user interaction?
Thanks in advance,
Filipe
Sorry, but no, you cannot launch an iOS to the foreground programmatically. The design of iOS forbids this, as it always requires a user to gesture to allow an app to cone to the foreground. The closest you can come is sending a local notification as you have done. Tapping the local notification is the simplest and most user-friendly way to get that required user gesture.
What I want that, I set the local notification for 7:00 am and as its fire immediately, notification comes continuously till the user not perform any action on notification or open the app.
below is code to send notification first time
let alarmNotification: UNMutableNotificationContent = UNMutableNotificationContent()
alarmNotification.title = "Demo"
alarmNotification.body = "Test"
alarmNotification.categoryIdentifier = "myDemoCategory"
let now = Date()
let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute], from: now)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let request = UNNotificationRequest(identifier: "TestNotification\(now)", content: alarmNotification, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
Please suggest for continuous send local notification.
Thanks
In your date component add seconds here
let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute], from: now)
set number of notifications you want in loop for every second by incrementing seconds Max is 64 in iOS.
when notification is tapped dismiss all notifications and reset for next time.
I'm new to WatchKit development. I would like to display a message regardless of what app is currently being used or whether the watch is active or not, like how the built-in Timer app shows the label "Timer Done". The user should then be able to click an "OK" button and dismiss the message.
I have tried using both alerts and modal views, but showing them programmatically still requires my app to be active. Using the notifications system is not a viable solution because that would rely on an iPhone.
I've been stuck on this for many hours, any insight would be helpful, thanks.
You need to ask permission in your iOS App first:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound])
{ (granted, error) in
if !granted
{
print("User did not give permissions to send notitications...")
}
}
Then in your watchOS App you can create a notification for some time in the future, make sure you give it a UUID (this may be a bug in watchOS3):
let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.title = "Title"
content.subtitle = "Subtitle"
content.body = "message"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "aCategory"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: duration, repeats: false)
let id: String = WatchNotify.getUUID()
let request = UNNotificationRequest.init(identifier: id,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
{
(error) in // ...
}
....
class func getUUID() -> String
{
let uuidObj = CFUUIDCreate(nil)
let uuidString = CFUUIDCreateString(nil, uuidObj)!
return uuidString as String
}