1
我正在尝试设置一个函数,该函数将在接下来的n天内接收一个整数并计划本地通知。我收到一个错误,我无法将Date类型转换为DateComponents。我一直无法弄清楚如何转换它。我发现了一些其他类似的问题here和here,但我还没有能够适应这些答案在Swift 3上工作。将日期转换为DateComponents函数来安排Swift中的本地通知3
如何将Date转换为DateComponents?有没有更好的方式来安排通知?
在此先感谢您的帮助:)
有错误的路线,“无法将类型的价值‘日期?’预期参数类型 'DateComponents'“:
let trigger = UNCalendarNotificationTrigger(dateMatching: fireDateOfNotification, repeats: false)
全功能:
func scheduleNotification(day:Int) {
let date = Date()
let calendar = Calendar.current
var components = calendar.dateComponents([.day, .month, .year], from: date as Date)
let tempDate = calendar.date(from: components)
var comps = DateComponents()
//set future day variable
comps.day = day
//set date to fire alert
let fireDateOfNotification = calendar.date(byAdding: comps as DateComponents, to: tempDate!)
let trigger = UNCalendarNotificationTrigger(dateMatching: fireDateOfNotification, repeats: false) //THIS LINE CAUSES ERROR
let content = UNMutableNotificationContent()
content.title = "New Alert Title"
content.body = "Body of alert"
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "alertNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
谢谢你,这个修正错误,是不是我的代码要简单得多。我试图让它复杂化。 – tylerSF