Reputation: 1061
I'm setting up some local notifications as reminders. So far I've been able to set a non repeating notification which triggers from a date picked from a datePicker.
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.medium
dateformatter.timeStyle = DateFormatter.Style.short
let dateFromString = dateformatter.date(from: selectDateTextField.text!)
let fireDateOfNotification: Date = dateFromString!
//if permission allowed
let content = UNMutableNotificationContent()
content.title = notifTitleTextField.text!
content.body = notifNoteTextView.text
content.sound = UNNotificationSound.default()
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: fireDateOfNotification)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
repeats: false)
//Schedule the Notification
let titleNospace = notifTitleTextField.text?.replacingOccurrences(of: " ", with: "")
let identifier = titleNospace
let request = UNNotificationRequest(identifier: identifier!, content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: { (error) in
if let error = error {
print(error.localizedDescription)
}
})
Now i would like the user to pick from a list (or a Picker) the repeating interval (hourly, daily, weekly, monthly, yearly or every x days). Is there a simple way to do so or i need to create a custom class? is it correct to make it through a series of if else statement? (it seems to me a bit off, doesn't really seems to be the correct way) Thanks.
Upvotes: 2
Views: 1512
Reputation: 54795
If you set up a UNCalendarNotificatonTrigger
, you cannot manipulate its repetition interval when you set repeats = true
, since it will be repeating at each date when the date components of the trigger are matched. To give you an example, if you only set up the hour, minute and second
components, your notification will be repeated daily, since the exact hour, minute and second values occur each day. If you only set up minute and second
, the notification will repeat every hour.
What you are looking for is the UNTimeIntervalNotificationTrigger
, this is the one using which you can set up the repetition interval.
However, to match your criteria, you need to mix both triggers. You should first set up a non-repeating UNCalendarNotificationTrigger
and once that notification is delivered, set up a repeating UNTimeIntervalNotificationTrigger
with the time interval coming from the user. See UNTimeIntervalNotificationTrigger
Upvotes: 2