Search code examples
iosswifteventkit

Swift 4.2 EventKit get all Events to the selected calendar on TableView didSelectedRowAt


I'm loading all my calendars in a tableview where every calendar is represented in a cell. Now I want to print all the events of the calendar of the cell when I tap the cell. The Problem is, with the code you see I get the events of all calendars.

How can I tell the function only to look in the calendar I tapped in tableview?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let calendarTitle = calendars![indexPath.row].title
    print(calendarTitle)
    let calendar = Calendar.current
    print("Current \(calendar)")

    var oneDayAgoComponents = DateComponents()
    oneDayAgoComponents.day = -1
    let oneDayAgo = calendar.date(byAdding: oneDayAgoComponents, to: Date())

    var oneDayFromNowComponents = DateComponents()
    oneDayFromNowComponents.day = 7
    let oneDayFromNow = calendar.date(byAdding: oneDayFromNowComponents, to: Date())

    var predicate: NSPredicate? = nil
    if let anAgo = oneDayAgo, let aNow = oneDayFromNow {
        predicate = eventStore.predicateForEvents(withStart: anAgo, end: aNow, calendars: nil)

    }

    var events: [EKEvent]? = nil
    if let aPredicate = predicate {
        events = eventStore.events(matching: aPredicate)

        for event in events! {
            print(event.title)
        }
    }
}

Solution

  • You have to pass the calendar in the calendars parameter of predicateForEvents

    let rowCalendar = calendars![indexPath.row]
    let calendarTitle = rowCalendar.title
    print(calendarTitle)
    
    ...
    
    if let anAgo = oneDayAgo, let aNow = oneDayFromNow {
        predicate = eventStore.predicateForEvents(withStart: anAgo, end: aNow, calendars: [rowCalendar])
    }
    

    And please declare the data source array as non-optional empty array as you are force unwrapping it anyway

    var calendars = [EKCalendar]()