swift - 无法快速将特定日期和时间添加到 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
如何设置从日期选择器到文本字段的特定日期和时间的通知。请帮我写代码
解决方案
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 = ...
推荐阅读
- c++ - 在 C++ 中将 HEX 字符串转换为 long
- javascript - 带有动态键的 JS SetInterval 未清除
- node.js - 是否可以在图像保存/上传之前使用 Multer 获取图像尺寸(宽度和高度)
- python - 加入两个表,文件名有额外的字符串,正则表达式从文件名中删除字符串并进行连接
- java - Android Studio 替换了我的 main.dart 文件中的代码
- c# - C#:使用 IQueryable 注入 DbContext 时无法访问 ASP.NET Core 中的已处置对象
- java - 启动 tomcat 失败并出现无效字节码错误
- python - 为什么我的 python 重复功能不起作用?
- sql - 如何执行与实际统计信息相同的查询结果
- azure - azure 中是否有确保默认启用数据库审核的策略