首页 > 解决方案 > 使用自定义间隔安排本地通知

问题描述

我有以下问题: 我希望用户可以设置一个时间间隔(例如 1 周、2 周、3 周、4 周等等......)。如果此时间间隔过去,则应触发通知并向用户显示某些内容。

这是我安排通知的代码(目标是我的自定义对象):

func scheduleNewNotification(for goal : Goal, at trigger : DateComponents) {
        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = NSLocalizedString("time", comment: "")
        notificationContent.body = "\(goal.name) " + NSLocalizedString("notifyBody", comment: "")
        notificationContent.sound = UNNotificationSound.default
        
        let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: trigger, repeats: true)
        let request = UNNotificationRequest(identifier: goal.name, content: notificationContent, trigger: notificationTrigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

每次我想安排通知时,我都会调用此代码:

func configureTrigger() -> DateComponents {
        var date = DateComponents()
        switch selectedInterval {
        case .weekly:
             // return configured date
             break
        case .twoWeeks:
             // return configured date
             break
        // and so on ...

        default:
            break
        }
        return date
    }

例如,当 switch 案例到达 .weekly 时,我希望它以我只需将其传递给我的 scheduleNewNotification() 的方式配置 DateComponents,以便用户在每个选定的时间间隔收到通知。

这甚至可能仅使用 DateComponents 吗?

标签: iosswiftuilocalnotification

解决方案


推荐阅读