How to create dateComponents from Date stored in CoreData

╄→尐↘猪︶ㄣ 提交于 2019-12-24 21:52:18

问题


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.

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.

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

Optional(2)

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


回答1:


Explicit cast it like this

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



回答2:


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



来源:https://stackoverflow.com/questions/48244556/how-to-create-datecomponents-from-date-stored-in-coredata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!