【问题标题】:How to create dateComponents from Date stored in CoreData如何从存储在 CoreData 中的日期创建 dateComponents
【发布时间】:2018-06-22 23:54:03
【问题描述】:

我正在尝试从 UIDatePicker 中存储在 CoreData 中的日期创建 dateComponents。但是,我无法做到。我首先将存储在editnotes?.sSelectedDate 中的日期转换为dateComponents,然后使用 dateComponents 触发我的通知。

这是我正在做的事情:

 var date = Date()
        if let editnote = editnotes
        {
           date = editnote.sSelectedDate
        }
        else
        {
            print("nil")
        }
        let calendar = NSCalendar.current
        let unitFlags = Set<Calendar.Component>([.day, .month, .year, .hour, .minute])
        let anchorComponents = calendar.dateComponents(unitFlags, from: date)
        var dateInfo1 = DateComponents()
        dateInfo1.day = anchorComponents.day
        dateInfo1.month = anchorComponents.month
        dateInfo1.hour = anchorComponents.hour
        dateInfo1.minute = anchorComponents.minute
        dateInfo1.year = anchorComponents.year
        let trigger = UNCalendarNotificationTrigger(dateMatching:dateInfo1, repeats: false)

我正在这样做:

if let editnote = editnotes
        {
           date = editnote.sSelectedDate
        }
        else
        {
            print("nil")
        }

解开可选的,但它仍然无法正常工作。继续阅读!

我知道我可以使用 anchorComponents 但这不起作用,所以我将它们复制到一个新的 DataComponents 实例中。

我正在尝试打印存储在dateInfo1.hour 中的内容,我得到了

可选(2)

我认为这就是 dateComponents 无法在预定时间触发通知的原因。 帮助将不胜感激?

【问题讨论】:

    标签: ios core-data nsmanagedobject nsdatecomponents usernotifications


    【解决方案1】:

    像这样显式转换

    let anchorComponents = calendar.dateComponents(unitFlags, from: date) as! DateComponents
    

    【讨论】:

    • 能否详细说明。
    • 试过了!还是行不通。不要认为它的可选问题tbh。还有其他问题!
    【解决方案2】:

    您使用的是anchorComponents.days / .hours / .days / .minutes,这都是可选的。相反,我使用了 DateComponents 的初始化程序,您可以在其中明确设置所需的属性。但我认为你只是做错了什么,这就是为什么通知不起作用,原因不是日期。您可以通过设置从日期到当前日期加上几秒钟来简单地检查它,看看您是否会收到通知

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多