3

In my app, i want to add local notifications. The scenario will be that the user can select any time and days from Mon to Sun. For example, if the user selects Mon, Thur and Sat as days and time as 11:00 pm, so now the user should be notified at all the selected days and that particular time.

Code:

 let notification = UNMutableNotificationContent()
 notification.title = "Danger Will Robinson"
 notification.subtitle = "Something This Way Comes"
 notification.body = "I need to tell you something, but first read this."

 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
 // let test = UNCalendarNotificationTrigger()
 let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
 UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

I am using this code but this doesn't work according to what I need.

joern
  • 27,354
  • 7
  • 90
  • 105
Sonali Pawar
  • 420
  • 3
  • 18
  • Your timeInterval in this code is 60seconds. So, it will fire after 60seconds. You didn't implemented any logic of triggering it on multiple days? – Aditya Srivastava Sep 07 '17 at 05:58
  • Something like https://stackoverflow.com/questions/41800189/local-notifications-repeat-interval-in-swift-3 looks interesting – MadProgrammer Sep 07 '17 at 06:03

1 Answers1

8

To get local notifications that repeat on a certain weekday at a certain time you can use a UNCalendarNotificationTrigger:

let notification = UNMutableNotificationContent()
notification.title = "Danger Will Robinson"
notification.subtitle = "Something This Way Comes"
notification.body = "I need to tell you something, but first read this."

// add notification for Mondays at 11:00 a.m.
var dateComponents = DateComponents()
dateComponents.weekday = 2
dateComponents.hour = 11
dateComponents.minute = 0
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

If you want notifications on Monday, Thursday and Saturday at 11:00 you need to add 3 separate requests. To be able to remove them you have to keep track of the identifiers.

joern
  • 27,354
  • 7
  • 90
  • 105
  • Great Answer! Thanks. I have a Question, Do you know how can I stop repeating this notification in certain time? – Mohamed Ezzat Aug 12 '18 at 15:06
  • @MohamedEzzat You can set the notification request’s identifier property and remove it from Notification Center using that identifier at any time. – joern Aug 12 '18 at 20:55