本文介绍了如何从CoreData中存储的日期创建dateComponents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create dateComponents from Date stored in CoreData from UIDatePicker. However, I am not able to make it. I am first converting Date which is stored in editnotes?.sSelectedDate into dateComponents and then using the dateComponents for triggering my notifications.

这是我在做什么:

 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")
        }

解开可选内容,但仍无法正常工作。继续阅读!

to unwrap the optional but it's not working still. Continue reading!

我知道我可以使用anchorComponents,但是那没有用,所以我将它们复制到了一个新的DataComponents实例中。

I know I can use anchorComponents but that wasn't working so I copied those into a new DataComponents instance.

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

I am trying to print the what is stored indateInfo1.hour and I get

我认为这就是为什么dateComponents无法在计划的时间触发通知。
帮助会受到赞赏吗?

I reckon this is the reason why dateComponents is not working for triggering notifications at scheduled time.Help will be appreciated?

推荐答案

您正在使用 anchorComponents.days / .hours / .days / .minutes 都是可选的。取而代之的是,我在 DateComponents 中使用了初始化程序,您在其中明确设置了所需的属性。但是我认为您只是在做错什么,这就是为什么通知无法正常运行且原因还不是过时的原因。您只需将日期设置为当前日期再加上几秒钟即可检查它,以查看是否会收到通知

You'r using anchorComponents.days / .hours / .days / .minutes it's all optional. Instead, I'd used initialiser for DateComponents where you explicitly set your properties you needed. But I think you'r just doing something wrong and that's why notification not working and the reason is not date. You can simply check it by setting from date to current date plus few seconds to see whether you'll get notification or not

这篇关于如何从CoreData中存储的日期创建dateComponents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 22:24