Start and End date in UNNotificationRequest

276 views Asked by At

How to schedule a local notification request with the future start date(with Time) and end date(with Time). is it possible as I am unable to see any variable in the framework

1

There are 1 answers

1
Nitanta Adhikari On
            let formatter = DateFormatter()
            formatter.dateStyle = .long
            formatter.dateFormat = "dd MMM yyyy HH:mm"
            
            guard let startDate = formatter.date(from: "03 Sep 2021 09:40")
            , let endDate = formatter.date(from: "03 Sep 2021 10:40") else { return }
            
            let intervalBetweenNotifications: Double = 5 * 60 // 5 minutes
            
            for item in stride(from: startDate.timeIntervalSinceNow, to: endDate.timeIntervalSinceNow, by: intervalBetweenNotifications) {
                let objectId = UUID().uuidString
                let content = UNMutableNotificationContent()
                content.title = "Title of the notification"
                content.sound = .default
                content.threadIdentifier = objectId
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: item, repeats: false)
                let request = UNNotificationRequest(identifier: objectId, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            }

You can change the start, end date and the interval between consecutive notifications.