Swift 4 How to get all events from calendar?

无人久伴 提交于 2019-12-04 16:42:26

After spending so much time, i got a solution to my problem. My problem was as below,

event start date 2019-03-15 09:00:00 +0000
event end date 2019-03-15 14:00:00 +0000

the predicate as below,

CADEventPredicate start:15/03/19, 1:30 PM; end:15/03/19, 7:30 PM; cals:(null)

As i am from India, the predicate is adding GMT+5:30 to my actual event start and end time. I got a method from stack overflow, to convert to local & global timezone as below.

    extension Date {
    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
}

While passing start and end date with time to predicate i am converting to globalTimeZone as below.

let predicate = eventStore.predicateForEvents(withStart: eventStartDateTime.toGlobalTime(), end: eventEndDateTime.toGlobalTime(), calendars: nil)

If you don't have time, you have only start & end dates, then use predicate as below,

event start date 2019-03-15 00:00:00 +0000
event end date 2019-03-15 00:00:00 +0000

let predicate = eventStore.predicateForEvents(withStart: eventStartDateTime, end: eventEndDateTime, calendars: nil)

Because if you don't have time and converting to globalTimeZone, you may face issues in deleting the events.

I hope it will help some one.

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