A.Roe
A.Roe

Reputation: 1095

Local UNMutableNotificationContent fire date using Date picker

So I have been trying to implement iOS 10 Local Notifications, first I thought the code is the same as iOS 9 just adding a notification extension target. However it actually uses the UNMutableNotificationContent class,

I can set a notification with a notification using a time interval however how can I specifically set the fire date using a date picker ?

import UserNotifications

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let displayDate  = dateFormatter.string(from: datePicker.date)

let notif = UNMutableNotificationContent()

notif.title = "Reminder)"
notif.subtitle = "\(displayDate)"
notif.body = "Details"
notif.categoryIdentifier = "Details Reminder"

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: notifTrigger)

The UNNotificationRequest trigger requires a type UNTimeIntervalNotificationTrigger which I was hoping i could just add a date.

Would I have to work out the interval time using the current date and the date picker date ? Or could I do this some other way

Upvotes: 1

Views: 2493

Answers (2)

DS.
DS.

Reputation: 3004

You should use UNCalendarNotificationTrigger.

UNCalendarNotificationTrigger.init(dateMatching: NSCalendar.current.dateComponents([.day, .month, .year, .hour, .minute], from: <<YOUR_DATE>>), repeats: false)

Upvotes: 2

Michael
Michael

Reputation: 9044

You need to provide the time interval between 'now' and when you want the notification to be sent.

let interval = laterDate.timeIntervalSince(earlierDate)

In this case, earlierDate should be 'now' (ie. just Date()), and I assume laterDate is your datePicker.date.

Upvotes: 5

Related Questions