Mój kod używa datePicker
, który zmienia się po zmianie datePicker
i odpowiada aktualnej dacie urządzenia użytkownika. Wystrzeliwuje powiadomienie. Jednak AVSpeechUtterance
używam ognia, gdy tylko zmieni się czas datePickers
, a nie kiedy pojawi się powiadomienie. Chciałbym, aby AVSpeechUtterance
i powiadomienie były uruchamiane w tym samym czasie.wywołać akcję po wyświetleniu powiadomienia (swift3)
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)
}}
APP DELEAGATE
import AVFoundation
import UIKit
import UserNotifications
enum NotificationName: String {
case mySpeechNotification
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if error != nil {
print("Ops, error trying to get authorization")
} else {
if !granted {
print("Dude, let me use notifications!")
}
}
}
}
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Oh, will present a notification, let's see the identifier: \(notification.request.identifier)")
if (notification.request.identifier == NotificationName.mySpeechNotification.rawValue) {
print("Speaking...")
} else {
print("Nothing to say...")
}
completionHandler(.alert)
let begin = AVSpeechUtterance(string: " Hello ")
begin.voice = AVSpeechSynthesisVoice(language: "en-US")
begin.rate = 0.08
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(begin)
}
}
Dam ci punkty, jeśli pokażesz mi, jak to zrealizować. Czy muszę wdrożyć delegata tej aplikacji? –
Zaktualizowano odpowiedź, sprawdź. – valcanaia
Czy umieściłem mój kod mowy w delegacie aplikacji lub vc. –