Fire action only after notification appears (swift3)

My code uses a datePicker, that when the datePicker is changed and matches the current date of the user device. It fires a notification. However the AVSpeechUtterance I am using fires as soon as the datePickers time is changed not when the notification appears. I would like the AVSpeechUtterance and notification to be be fired at the same time.

    import UIKit
    import  AVFoundation
   import UserNotifications

   class ViewController: UIViewController {
 @IBOutlet var datePicker: UIDatePicker!

   @IBAction func datePicker(_ sender: Any) {
let c = UNMutableNotificationContent()
c.title = "Lets Roll"
c.subtitle  = "s"
c.body = "d"

let begin = AVSpeechUtterance(string: " Hello ")

let synthesizer = AVSpeechSynthesizer()

begin.voice = AVSpeechSynthesisVoice(language: "en-US")
begin.rate = 0.08

synthesizer.speak(begin)

let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: datePicker.date )
let t = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let r = UNNotificationRequest(identifier: "any", content: c, trigger: t)

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

Hi @zalubski

You can move this code:

let begin = AVSpeechUtterance(string: " Hello ")
let synthesizer = AVSpeechSynthesizer()
begin.voice = AVSpeechSynthesisVoice(language: "en-US")
begin.rate = 0.08
synthesizer.speak(begin)

To this delegate method of UNUserNotificationCenterDelegate:

userNotificationCenter(_:willPresent:withCompletionHandler:)

Note it will work only when your app is in foreground.

Nikita

Thanks for your help.

I dont know how to call this function.

You shouldn’t call it. It is called automatically when your app receives a notification and your app is in the foreground.
You need to declare your AppDelegate as UNUserNotificationCenterDelegate and implement two methods of that protocol.
Here is an example:

Nikita