首页 > 解决方案 > 无法快速将特定日期和时间添加到 UserNotifications

问题描述

我从 Datepicker 到 textfield 获取日期和时间.. 我需要设置通知的日期和时间.. 我已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

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

标签: swiftdatepickercalendaruilocalnotification

解决方案


Your code seems OK.

How are you testing the notification (reminder)? if you just manually change your device date to the desired date, but more than 15 minutes away from the exact time -> you won't see a notification! Try to jump to a minute before the expected notification time and then move to the next minute (or wait:)). This may be tricky if you don't set hour/minute so it becomes 00:00.

Also, if you want to be sure, you can set DateComponents explicitly:

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

推荐阅读