Almudhafar
Almudhafar

Reputation: 887

Swift Repeat LocalNotification every 5 days

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)

Upvotes: 3

Views: 2659

Answers (1)

Rashed
Rashed

Reputation: 2425

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.

Upvotes: 5

Related Questions