【问题标题】:Using Timer To Schedule Notifications Triggering使用计时器安排通知触发
【发布时间】:2018-09-13 12:34:36
【问题描述】:

我正在尝试根据用户在 UIDatePicker 中选择的内容来安排计时器在特定日期和时间触发。当计时器触发时,我想每 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】:
    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()
       }
    }
    

    这是您刚刚分配错误时间间隔的工作代码 :)

    【讨论】:

    • 你是说UNTimeIntervalNotificationTrigger中的timerInterval关闭了?当我在不使用 Timer 的情况下进行测试时,它正在工作。我认为计时器可能是问题
    • @JDub 我使用了与你的问题相同的计时器代码,除了 datePicker.date 是我当前的 Date()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2019-06-25
    • 1970-01-01
    • 2020-06-06
    相关资源
    最近更新 更多