Использование таймера для планирования запуска уведомлений - PullRequest
0 голосов
/ 13 сентября 2018

Я пытаюсь запланировать запуск таймера на определенную дату и время в зависимости от того, что пользователь выбирает в UIDatePicker. Когда срабатывает таймер, я хочу настроить повторяющееся уведомление (UNTimeIntervalNotificationTrigger) каждые 60 секунд. Таймер, кажется, срабатывает, и консоль показывает, что уведомление добавляется без ошибок, но я никогда не получаю уведомление. Что я делаю не так?

@IBAction func triggerNotification(_ sender: Any) {
    if (reminderText.text!.count > 0)
    {
        let timer = Timer(fireAt: datePicker.date, interval: 0, target: self, selector: #selector(setUpReminder), userInfo: nil, repeats: false)
        RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
        self.dismiss(animated: true, completion: nil)
        reminderText.text = ""
    }
}
@objc func setUpReminder()
{
    let content = UNMutableNotificationContent()
    let identifier = reminderText.text!
    content.title = "Your Reminder"
    content.body = identifier
    content.badge = 1
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60.0, repeats: true)
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request){
        (error) in
        if error != nil
        {
            print("here error in setting up notification")
            print(error!)
        } else
        {
            print("notification scheduled")
        }
    }
}

1 Ответ

0 голосов
/ 13 сентября 2018
func sendNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Timer"
    content.body = "30 Seconds"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.001, repeats: false)
    let request = UNNotificationRequest(identifier: "timer.request", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error{
            print("Error posting notification:\(error.localizedDescription)")
        } else{
            print("notification scheduled")
        }
    }
}


@objc func setUpReminder()
{
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound])
    {(granted, error) in

       self.sendNotification()
   }
}

это рабочий код, который вы просто присваивали неверному интервалу времени:)

...