-->

How to show multiple local notifications?

2019-08-15 04:40发布

问题:

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

回答1:

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))")
                            }
                        })