简体   繁体   English

iOS 基于用户在 ToDo DatePicker (Swift & SwiftUI) 中设置的日期时间的本地通知

[英]iOS Local Notification based on date time set by user in ToDo DatePicker (Swift & SwiftUI)

I'm learning by applying and have been able to build up a todo app with title, priority and due date and pass that through core data and display it on a list view.我通过申请来学习,并且已经能够构建一个带有标题、优先级和截止日期的待办事项应用程序,并将其传递给核心数据并将其显示在列表视图中。

At this point using the following code.此时使用以下代码。 I've been able to launch a pop up requesting user consent for notifications.我已经能够启动一个弹出窗口,请求用户同意通知。

Function Used Function 二手

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)
        }
    }
}

Called in Content View using在内容视图中使用

.onAppear(perform: requestPush)

At this point I've tried several solutions to use the date from the date picker for each todo item and set a reminder.在这一点上,我已经尝试了几种解决方案来为每个待办事项使用日期选择器中的日期并设置提醒。 However I am not able to get the schedule Local Notification function to work.但是,我无法安排本地通知 function 工作。

Here is what I've been working with so far.这是我迄今为止一直在使用的。

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)")
        }
    }
}

Any suggestions or guidance on how I can set up local notifications based on each todo item due date?关于如何根据每个待办事项到期日设置本地通知的任何建议或指导?

Note: Codes are based on various solutions available on the web.注意:代码基于 web 上可用的各种解决方案。 This is the one that worked for me to the point of collecting user approval for notifications.这是一个对我有用的方法,可以收集用户对通知的批准。

It's difficult to say without seeing the whole code and possibility to debug what exactly wrong, so I wrote small example here https://github.com/yellow-cap/swiftui-local-notifications .如果没有看到完整的代码和调试错误的可能性很难说,所以我在这里写了一个小例子https://github.com/yellow-cap/swiftui-local-notifications

The main files to explore: LocalNotificationsApp.swift , NotificationManager.swift , ContentView.swift要探索的主要文件: LocalNotificationsApp.swiftNotificationManager.swiftContentView.swift

If you will have any questions, feel free to ask.如果您有任何问题,请随时提问。

UPDATED AFTER CODE REVIEW:代码审查后更新:

Schedule notification action安排通知操作

    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)
}

Notification manager scheduleNotification function:通知管理器 scheduleNotification function:

    func scheduleNotification(id: String, content: UNNotificationContent, trigger: UNNotificationTrigger) {
        let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
        notificationCenter.add(request)
}

Full code of the NotificationManager: https://github.com/yellow-cap/swiftui-local-notifications/blob/main/LocalNotifications/LocalNotifications/NotificationManager.swift NotificationManager 的完整代码: https://github.com/yellow-cap/swiftui-local-notifications/blob/main/LocalNotifications/LocalNotifications/NotificationManager.swift

i suspect its not work because date comparison statement.我怀疑它不起作用,因为日期比较声明。

if setReminder < Date() {
        if let addedValue = Calendar.current.date(byAdding: .minute, value: 1, to: setReminder) {
            setReminder = addedValue
        }
    }

should be应该

var setReminder = Date().addingTimeInterval(10)    
let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: setReminder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM