简体   繁体   English

如何从CoreData中存储的日期创建dateComponents

[英]How to create dateComponents from Date stored in CoreData

I am trying to create dateComponents from Date stored in CoreData from UIDatePicker. 我正在尝试从UIDatePicker的CoreData中存储的日期创建dateComponents。 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. 我首先将存储在editnotes?.sSelectedDate转换为dateComponents ,然后使用dateComponents触发我的通知。

Here is what I am doing: 这是我在做什么:

 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)

I am doing this: 我正在这样做:

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

to unwrap the optional but it's not working still. 打开可选组件,但仍无法正常工作。 Continue reading! 继续阅读!

I know I can use anchorComponents but that wasn't working so I copied those into a new DataComponents instance. 我知道我可以使用anchorComponents,但是那没有用,所以我将它们复制到了一个新的DataComponents实例中。

I am trying to print the what is stored in dateInfo1.hour and I get 我正在尝试打印存储在dateInfo1.hour ,我得到了

Optional(2) 可选的(2)

I reckon this is the reason why dateComponents is not working for triggering notifications at scheduled time. 我认为这是dateComponents无法在计划的时间触发通知的原因。 Help will be appreciated? 帮助将不胜感激?

像这样显式投射

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

You'r using anchorComponents.days / .hours / .days / .minutes it's all optional. 您正在使用anchorComponents.days / .hours / .days / .minutes这都是可选的。 Instead, I'd used initialiser for DateComponents where you explicitly set your properties you needed. 相反,我使用了DateComponents初始化程序,在其中您明确设置了所需的属性。 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 您只需将日期设置为当前日期再加上几秒钟即可进行检查,以查看是否会收到通知

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM