Waqar Khalid
Waqar Khalid

Reputation: 119

Repeat UNNotifications every day and every half hour

I want to show local notifications to user between selected hours from user and repeat that notification for every half hour till the limit of the selected hour comes and also repeat this notification daily. I have used this code

let components = calendar.dateComponents(in: .current, from: date)
     var triggerDate = DateComponents()
            triggerDate.hour = components.hour
            triggerDate.minute = components.minute
            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

But this only repeats the notification daily at that specific time selected by user but I want to repeat this also at every half hour from that specific time.I have used UNNotifications.Any help will be much appreciated.Thanks

Upvotes: 0

Views: 912

Answers (1)

Nikhlesh Bagdiya
Nikhlesh Bagdiya

Reputation: 4466

If you want to show local notifications for every half hour between selected hours then you have to set different notification for every hour with different notification identifier as:

var dateStart = "Pass Your Start Date for Notification."
let dateEnd = "Pass Your End Date for Notification."

//Check Start Date is less then End Date is not.        
while dateStart < dateEnd {

     dateStart = dateStart.addingTimeInterval(0.5 * 60 * 60) //Add half an hour to start time

    //Schedule notification With body and title.
    scheduleNotification(at: dateStart, body: "Show Me", titles: "Remainder")

}

Implement Notification by following function as:

//Schedule Notification with Daily bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

    let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: date)

    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

    let content = UNMutableNotificationContent()
    content.title = titles
    content.body = body
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "todoList"

    let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
  //UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("Uh oh! We had an error: \(error)")
        }
    }
}

Pass start Date in dateStart variable and Date End Date in dateEnd variable.

Upvotes: 3

Related Questions