ios - 使用计时器安排通知触发
问题描述
我正在尝试根据用户在 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")
}
}
}
解决方案
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()
}
}
这是您刚刚分配错误时间间隔的工作代码:)
推荐阅读
- wordpress - 输入数量的产品页面的 URL - WooCommerce
- sql-server - 在 SSRS 2012 中导出为 CSV 时如何创建标题
- mongodb - 时刻js没有在猫鼬中更新
- angular - 有没有办法在图像路径中使用 angular base href 作为变量?
- python - 使用 selenium python 和 Firefox 重新打开相同的浏览器窗口
- module - 字符设备读取命令无限打印(通过cat命令)
- selenium - 如何基于 Chrome 开发工具中的元素编写 XPath?
- javascript - 无法从 JS 中的嵌套函数调用访问迭代项
- winapi - 动态数据交换 (DDE) 链路终止
- c++ - PostgreSQL:如何为我的单元测试创建一个临时用户和数据库?