swift - 我想设置每日提醒(本地通知)以及用户输入按钮后 10 秒的提醒
问题描述
目前,即使我将UNCalendarNotificationTrigger's
repeat 属性更改为"true"
.
这是我的代码:
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Facts, tips, and tricks to help you quit:"
content.body = reminders.randomElement()!
content.sound = .default
content.userInfo = ["value": "Data with local notification"]
let fireDate = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: Date().addingTimeInterval(86400))
let trigger = UNCalendarNotificationTrigger(dateMatching: fireDate, repeats: true)
// UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)
let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request) { (error) in
if error != nil {
print("Error = \(error?.localizedDescription ?? "error local notification")")
}
}
它在一个IBAction
. 我希望它每天重复一次,并且在用户单击按钮后 10 秒也有一条消息。
这将如何实现?谢谢你。
解决方案
这就是您的操作方式:将当前日期(当您点击按钮时)转换为日期组件,并为每天的特定时间安排通知。
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Facts, tips, and tricks to help you quit:"
content.body = reminders.randomElement()!
content.sound = .default
content.userInfo = ["value": "Data with local notification"]
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request)
推荐阅读
- pandas - Powerquery / Pandas - Outlook邮箱响应时间(表格设计)
- php - 无法使用php将照片存储在数据库中
- vuejs2 - 我应该担心由于不删除事件处理程序而导致的内存泄漏吗?
- python - 如何解码base64图像PIL
- computer-vision - ImportError:无法导入名称“get_dataset”
- php - 使用理论查询生成器检查值是否在两列之一中
- jquery - 第二个ajaxGet忽略变量上的.replace
- php - 编码“UTF8”的无效字节序列:0x89 PostgreSQL Laravel 8
- gitlab - Gitlab:使用来自组外的依赖代理?
- html - 使每个子元素都应用父 div 类