I am trying to read all calendar events from the EventStore. The routine I use, works sometimes but not always.
func getCalendarEvents(_ anfangOpt: Date?, _ endeOpt: Date?) -> [EKEvent]? {
guard let anfang = anfangOpt, let ende = endeOpt else { return nil }
var events: [EKEvent]? = nil
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion: { _,_ in })
if EKEventStore.authorizationStatus(for: EKEntityType.event) == EKAuthorizationStatus.authorized {
var predicate: NSPredicate? = nil
predicate = eventStore.predicateForEvents(withStart: anfang, end: ende, calendars: nil)
if let aPredicate = predicate {
events = eventStore.events(matching: aPredicate)
}
}
return events
}
This function always returns the events. But they are sometimes incomplete. So that
for event in bereinigteEvents {
if dateInInterval(prüfdatum, start: event.startDate, ende: event.endDate) {
istimurlaub = true
if let zwischenname = event.title {
eventname = zwischenname
} else {
eventname = "n/a"
}
eventcalendar = event.calendar.title
trigger.append ("Auslöser: „" + eventname + "“ im Kalender „" + eventcalendar + "“")
}
}
sometimes crashes at the line "eventcalendar = event.calendar.title" and the error message that "nil" was unexpectedly found.
Thank you!
After the first answer I have changed the function, which gets the events to:
func getCalendarEvents(_ anfangOpt: Date?, _ endeOpt: Date?) -> [EKEvent]? {
guard let anfang = anfangOpt, let ende = endeOpt else { return nil }
var events: [EKEvent]? = nil
let eventStore = EKEventStore()
func fetchEvents() {
var predicate: NSPredicate? = nil
predicate = eventStore.predicateForEvents(withStart: anfang, end: ende, calendars: nil)
if let aPredicate = predicate {
events = eventStore.events(matching: aPredicate)
}
}
if EKEventStore.authorizationStatus(for: EKEntityType.event) == EKAuthorizationStatus.authorized {
fetchEvents()
} else {
eventStore.requestAccess( to: EKEntityType.event, completion: {(granted, error) in
if (granted) && (error == nil) {
fetchEvents()
}
})
}
return events
}
But it still crashes with "unexpectedly found nil" in "event.calendar.title".
I ended up using this
Swift 4 How to get all events from calendar?
routine to fetch the events.
The problem still occurs sometimes (!!): Occasionally "nil" is found in "event.calender.title", although it shouldn't be "nil"