0

Basically, I need an app that runs a notification every other Monday. What I have is an app that runs a notification every Monday. Is there a way to set it up so that when the first notification is received the app will begin a two week time interval where it will run the notification again, and have it repeat? For example, if I had a variable called "week" and had it alternate between '1' and '2' every other week, how could I tag it to the notification's trigger?

func notification(hour: Int, minute: Int, weekday: Int, text: String){

    let content = UNMutableNotificationContent()
    content.title = "Example"
    content.body = text
    content.sound = UNNotificationSound.default()

    let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: hour, minute: minute, weekday: weekday), repeats: true)

    let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()

    notification(hour: 12, minute: 0, weekday: 2, text: "Test")

}
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93

1 Answers1

0

You cannot do that for repeated notifications. Only way to do this is to use non-repeated notifications and setup them on given time (in your case on Mondays) in advance - for example make a for-loop that will setup single notification on next 10 Mondays - you have to manually calculate trigger time for all of them in a loop.

Limitation is that you cannot make them infinitive - but probably if user will not react to those 10 notifications - there is a really small chance you use them later on - at least from my experience.

Best way to do this will be also to setup those notifications each time user closes the application - if we opens the app on 5th Monday for example, you should clean up all notifications and setup next set of 10 notifications again.

Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
  • Is there a way to change the 'repeat' interval in the trigger? – Jonathan Divens Sep 01 '18 at 21:36
  • You just go with UNCalendarNotificationTrigger with repeats = false and you have to generate it multiple times, each time calculating time trigger for next Monday in a row. So you need to use UNUserNotificationCenter.current().add as many time as many Mondays you want to cover in advance. – Grzegorz Krukowski Sep 01 '18 at 23:03