无法快速将特定的日期和时间添加到UserNotifications

问题描述

我正在从Datepicker到文本字段获取日期和时间。我需要设置通知的日期和时间。我在应用程序委托中添加requestAuthorization

通知代码,我尝试将datepicker日期提供给 dateComponents ,然后yourFireDate时间到来不正确

如果我给出日期和时间8/25/20,1:03 PM,那么yourFireDate总是像2020-08-24 18:30:00 +0000 一样出现,其余的也不会出现

 func displayReminderlocalnotification(body: String) {
    
    components = dtPicker.calendar.dateComponents([.day,.month,.year],from: dtPicker.date)
    day = components?.day
     month = components?.month
     year = components?.year
     hrs = components?.hour
    mins = components?.minute
    
    guard let yourFireDate = Calendar.current.date(from: components!) else { return }
    
    print("ihwdeiwqjheiq \(yourFireDate)")
    let content = UNMutableNotificationContent()
    content.title = Nsstring.localizedUserNotificationString(forKey:
                "Your notification title",arguments: nil)
    content.body = body
    content.categoryIdentifier = "Your notification category"
    content.sound = UNNotificationSound.default
    content.badge = 1

     let dateComponents = Calendar.current.dateComponents(Set(arrayLiteral: Calendar.Component.year,Calendar.Component.month,Calendar.Component.day,Calendar.Component.hour,Calendar.Component.minute),from: yourFireDate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,repeats: false)
    let request = UNNotificationRequest(identifier: "notification identifier",content: content,trigger: trigger)
    UNUserNotificationCenter.current().add(request,withCompletionHandler: nil)
}

这样我正在使用日期选择器:

 let dateFormatter       = DateFormatter()
  dateFormatter.dateStyle = DateFormatter.Style.short
  dateFormatter.timeStyle = DateFormatter.Style.short
  let strDate = dateFormatter.string(from: dtPicker.date)

   dateLabel.text = strDate

如何设置从日期选择器到文本字段的特定日期和时间的通知。请帮助我提供代码

解决方法

您的代码似乎还可以。

您如何测试通知(提醒)?如果您只是手动将设备日期更改为所需的日期,但距准确时间超过15分钟->您将不会收到通知!尝试在之前通知时间跳至一分钟,然后移至下一分钟(或等待:)。如果您未将小时/分钟设置为00:00,这可能会很棘手。

此外,如果您想确定的话,可以明确设置DateComponents

var dateComponents = DateComponents()
dateComponents.year = ...
dateComponents.month = ...
dateComponents.day = ...
dateComponents.hour = ...
dateComponents.minute = ...