iosswiftlocalnotificationunnotificationrequestunnotificationtrigger

Repeating local notification removes previous pending local notifications


I want to send local notification after every 30 minutes. I have implemented repeating local notification but it removes the preceding local notifications. The scenario is as explained : My client wants to get night alerts. He wants that when he wakes up in the morning he can check all the notification alerts at once.

Here is the code:

func application(_ application: UIApplication,  didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {didAllow,error in  })
    return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
    let content = UNMutableNotificationContent()
    content.title = "Hello"
    content.subtitle = "I am your local notification"
    content.body = "Yippppiiiieee...."
    content.badge = 1
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
    let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}

Solution

  • First you shouldn't use the same identifier as it removes already scheduled ones

     let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)
    

    second you have to insert different TimeInterval

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
    

    //

    (1...10).forEach {
    
        let content = UNMutableNotificationContent()
        content.title = "Hello \($0)"
        content.subtitle = "I am your local notification \($0)"
        content.body = "Yippppiiiieee.... \($0)"
        content.badge = 1
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval:TimeInterval($0*1800), repeats: false)
        let request = UNNotificationRequest(identifier: "testing\($0)", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
    }