Search code examples
iosswift3datepickernotificationsibaction

Use DatePicker to schedule notification (swift3)


I would like my user notification to appear when the user uses the datePicker action to select a date and time for the notification to appear.

 import UIKit
 import UserNotifications

 class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
       }

@IBAction func datePicker(_ sender: Any) {
}
@IBAction func disaper(_ sender: Any) {

    let c = UNMutableNotificationContent()
    c.title = "Lets Roll"
    c.subtitle  = "dx"
    c.body = "fyb"

    let t = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let r = UNNotificationRequest(identifier: "any", content: c, trigger: t)

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

}}

Solution

  • If you want to schedule a notification to be delivered at an exact date, you need to use UNCalendarNotificationTrigger instead of UNTimeIntervalNotificationTrigger. You should also set up an Outlet to the DatePicker, it makes setting up the notification trigger easier.

    let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: datePicker.date )
    let t = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)