0

I have this function that sets notifications but no matter which delayInterval I set, they fire at almost random intervals.
i.e. if I set delayInterval: 6000 the notification fires after 5 seconds and keeps repeating after 20 secs, 38 secs, 20 secs, 38 secs and so on. What's the problem?


class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        sendNotification(title: "Title", subtitle: "Subtitle", body: "Body", badge: 1, delayInterval: 6000)
    }

    func sendNotification(title: String, subtitle: String, body: String, badge: Int?, delayInterval: Int?) {

        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = title
        notificationContent.subtitle = subtitle
        notificationContent.body = body

        var delayTimeTrigger: UNTimeIntervalNotificationTrigger?

        if let delayInterval = delayInterval {
            delayTimeTrigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(delayInterval), repeats: true)
        }

        if let badge = badge {
            var currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber
            currentBadgeCount += badge
            notificationContent.badge = NSNumber(integerLiteral: currentBadgeCount)
        }

        notificationContent.sound = UNNotificationSound.default

        UNUserNotificationCenter.current().delegate = self

        let uuid = UUID().uuidString

        let request = UNNotificationRequest(identifier: uuid, content: notificationContent, trigger: delayTimeTrigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}
Francesco Leoni
  • 187
  • 2
  • 11
  • 1
    Hi, I would suggest to clean up all previous notifications before testing it so you can make sure that the notifications that you see were not previously scheduled. Like so - UNUserNotificationCenter.current().removeAllPendingNotificationRequests() – shbedev Nov 13 '19 at 11:23
  • Refer this: https://stackoverflow.com/questions/43405959/launch-a-local-notification-at-a-specific-time-in-ios – Dhaval Raval Nov 13 '19 at 11:28
  • @Sam Thank you that solved the problem – Francesco Leoni Nov 13 '19 at 12:16
  • Thanks for letting me know. Glad to help! – shbedev Nov 13 '19 at 12:17

0 Answers0