首页 > 解决方案 > 我想设置每日提醒(本地通知)以及用户输入按钮后 10 秒的提醒

问题描述

目前,即使我将UNCalendarNotificationTrigger'srepeat 属性更改为"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 秒也有一条消息。

这将如何实现?谢谢你。

标签: swiftxcode

解决方案


这就是您的操作方式:将当前日期(当您点击按钮时)转换为日期组件,并为每天的特定时间安排通知。

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)

推荐阅读