Search code examples
iosswiftiphoneuilocalnotificationios13

How does iOS Local Notification Queueing work for UNTimeIntervalNotificationTrigger?


If I create a simple app where I want one notification to be sent every minute for 4 consecutive minutes; after an initial 5 second delay.

When I call scheduleManyNotes() below, I print out the pending notifications and see only 1. What causes these notifications to be grouped together into 1?

func scheduleManyNotes() {

    for x in 0...4 {
        scheduleNote("note \(x)", (x * 60) + 5)
    }

    notificationCenter.getPendingNotificationRequests(completionHandler:{reqs in
        for request in reqs {
            print(request)
        }
    })
}

func scheduleNote(_ msg: String, _ delaySec: Int) {
    let content = UNMutableNotificationContent()
    content.sound = UNNotificationSound.default
    content.body = msg
    content.badge = NSNumber(integerLiteral: delaySec)
    content.categoryIdentifier = msg
    let trigger = delaySec == 0 ? nil : UNTimeIntervalNotificationTrigger(timeInterval: Double(delaySec), repeats: false)
    let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)

    NSLog("Scheduling Request \(msg)")

    notificationCenter.add(request) { (error) in
        if let error = error {
            NSLog("Error \(error.localizedDescription)")
        }
    }
}

Solution

  • The problem is that I was using the same identifier for all the TimeInterval notifications. One I changed the identifier to be unique for each request, I then had 5 unique requests.

    // Original
    
        let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
    
    
    // Modfified
    
        let uid = UUID.init().uuidString
        print("hopefully unique uuid:\(uid)")
        let request = UNNotificationRequest(identifier: uid, content: content, trigger: trigger)