【问题标题】:Convert Date to DateComponents in function to schedule local notification in Swift 3在函数中将 Date 转换为 DateComponents 以在 Swift 3 中安排本地通知
【发布时间】:2017-06-21 21:15:04
【问题描述】:

我正在尝试设置一个接收整数并在未来 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)")
        }
    }
 }

【问题讨论】:

    标签: ios swift unnotificationrequest


    【解决方案1】:

    我认为这个错误已经很清楚了。 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())
    

    【讨论】:

    • 谢谢,这修复了错误并且比我的代码简单得多。我试图把它复杂化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多