我正在通过应用学习,并且已经能够建立一个带有标题,优先级和到期日期的todo应用程序,并通过核心数据传递并将其显示在列表视图上。
此时使用以下代码。我已经能够启动一个弹出窗口,请求用户同意通知。
函数使用
func requestPush() -> Void {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
在内容视图中使用调用
.onAppear(perform: requestPush)
在这一点上,我已经尝试了几种解决方案,使用日期选择器中的日期为每个待办事项设置一个提醒。但是,我无法获得调度本地通知功能的工作。
这是我到目前为止一直在做的事情。
func scheduleNotification() -> Void{
let content = UNMutableNotificationContent()
content.title = "Your title"
content.body = "Your body"
var setReminder = Date()
if setReminder < Date() {
if let addedValue = Calendar.current.date(byAdding: .minute, value: 1, to: setReminder) {
setReminder = addedValue
}
}
let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: setReminder)
let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
let request = UNNotificationRequest(identifier: "alertNotificationUnique", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: (error)")
}
}
}
关于如何根据每个待办事项的截止日期设置本地通知,有什么建议或指导吗?注:代码基于网络上提供的各种解决方案。在收集用户对通知的批准这一点上,这对我来说是有效的。
在没有看到整个代码和调试可能性的情况下很难说到底哪里出了问题,所以我在这里写了一个小例子https://github.com/yellow-cap/swiftui-local-notifications。
主要探索的文件:LocalNotificationsApp.swift
,NotificationManager.swift
,ContentView.swift
如果你有任何问题,请提出来。
代码复查后更新:
调度通知动作
func scheduleNotification() {
let timeIntervalMinutes = 1
let notificationManager = // get NotificationManager
// create notification content
let content = UNMutableNotificationContent()
content.title = "Example title"
content.body = "Example body"
// create trigger (will show notification 1 min before selected time)
let triggerDate = self.setReminder.addingTimeInterval(Double(-timeIntervalMinutes * 60))
let trigger = UNCalendarNotificationTrigger(
dateMatching: Calendar.current.dateComponents([.timeZone, .year, .month, .day, .hour, .minute], from: triggerDate),
repeats: false
)
notificationManager.scheduleNotification(
id: "Example id",
content: content,
trigger: trigger)
}
通知管理器scheduleNotification功能:
func scheduleNotification(id: String, content: UNNotificationContent, trigger: UNNotificationTrigger) {
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
notificationCenter.add(request)
}
NotificationManager的完整代码:https://github.com/yellow-cap/swiftui-local-notifications/blob/main/LocalNotifications/LocalNotifications/NotificationManager.swift
我怀疑它不能工作,因为日期比较语句。
if setReminder < Date() {
if let addedValue = Calendar.current.date(byAdding: .minute, value: 1, to: setReminder) {
setReminder = addedValue
}
}
应该
var setReminder = Date().addingTimeInterval(10)
let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: setReminder)