ios – 将日期转换为DateComponents,以便在Swift 3中安排本地通知

我正在尝试设置一个接收整数的函数,并在将来的n天内安排本地通知.我收到一个错误,我无法将类型Date转换为DateComponents.我无法弄清楚如何转换它.我发现了一些其他类似的问题herehere,但我无法使这些答案适应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)")
        }
    }
 }
最佳答案
我认为错误是尽可能清楚的. UNCalendarNotificationTrigger是灵活的,因此您可以指定“在下周五触发触发器”.您需要的只是将下一个触发日转换为DateComponents:

let n = 7
let nextTriggerDate = Calendar.current.date(byAdding: .day, value: n, to: Date())!
let comps = Calendar.current.dateComponents([.year, .month, .day], from: nextTriggerDate)

let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
print(trigger.nextTriggerDate())

转载注明原文:ios – 将日期转换为DateComponents,以便在Swift 3中安排本地通知 - 代码日志