3

How to repeat LocalNotification every 5 days at 10:00 AM

I try this, but it's not working

let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "Hello_message_body"
content.sound = UNNotificationSound.default()

let futureTime = Date().addingTimeInterval(5 * 24 * 60 * 60)
var calendar = NSCalendar.current
calendar.timeZone = NSTimeZone.system
var components = calendar.dateComponents([.hour, .minute, .second], from: futureTime)
components.hour = 10
components.minute = 0
components.second = 0

let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "FiveDays", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
Almudhafar
  • 887
  • 1
  • 12
  • 26

1 Answers1

5

You can use UNCalendarNotificationTrigger to get Local Notification that repeats for any define days or week at any certain time.

let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Hello!"
//notificationContent.subtitle = "Something"
notificationContent.body = "Hello_message_body"
notificationContent.sound = UNNotificationSound.default

// Add notification for Friday (after 5 days) at 10:00 AM
var dateComponents = DateComponents()
dateComponents.weekday = 5
dateComponents.hour = 10
dateComponents.minute = 0

let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "notification1", content: notificationContent, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

Thank you.

karem_gohar
  • 336
  • 1
  • 3
  • 11
Rashed
  • 2,349
  • 11
  • 26
  • 1
    Hi!, I am using the same function but not getting notifications not even repeating notifications. – Aman Gupta Sep 26 '20 at 06:34
  • This will fire a notification every Thursday every week. In other words, the notification is scheduled to go off every 7 days and not ever 5 days (which is what desired goal as per the question seems). – Sbhambry Jul 09 '23 at 00:43