使用计时器安排通知触发

问题描述 投票:0回答:1

我试图根据用户在UIDatePicker中选择的内容,安排Timer在特定日期和时间触发。当计时器触发时,我想每隔60秒设置一次重复通知(UNTimeIntervalNotificationTrigger)。计时器似乎触发,控制台显示添加的通知没有错误,但我从未收到通知。我究竟做错了什么?

@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")
        }
    }
}
ios swift notifications nstimer
1个回答
0
投票
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()
   }
}

这是工作代码,你只是分配错误的时间间隔:)

© www.soinside.com 2019 - 2024. All rights reserved.