ios - 在函数中将 Date 转换为 DateComponents 以在 Swift 3 中安排本地通知

标签 ios swift unnotificationrequest

我正在尝试设置一个接受整数并在未来 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 具有灵 active ,因此您可以指定“在下周五触发触发器”。您只需将下一个触发日转换为 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 - 在函数中将 Date 转换为 DateComponents 以在 Swift 3 中安排本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042215/

相关文章:

ios - Ionic 插件开发最佳实践

ios - Swift 和方法原型(prototype)——前向声明

ios - 如何在 Swift 中使用组合图像创建 GMSMarker

ios - 基于缓存值可用性的运行方法

swift - 如何在 Swift 中取消本地通知触发器

ios - 我的 scrollView 剪切了我最后一张图片 Swift 3

ios - 通过导航 Controller 推送 Viewcontroller,显示黑屏

swift - 从 Storyboard (未嵌入)实例化的 Collection View 中未显示单元格

ios - 应用程序在后台时的 Firebase 监听器

ios - 当用户点击 iOS 中本地通知上的“查看”按钮时,如何设置 View ?