Search code examples
iosswiftcalendarnspredicateekeventkit

Text Search for iOS Calendar using EventKit


I need to search an iOS device calendar for calendar events that contain a given text in the event notes. Apple describes this procedure for a date filter, where the filter conditions are defined in an NSPredicate instance - as in the following example (from https://developer.apple.com/documentation/eventkit/retrieving_events_and_reminders#overview) and many others I could find.

var predicate: NSPredicate? = nil
if let anAgo = oneDayAgo, let aNow = oneYearFromNow {
    predicate = store.predicateForEvents(withStart: anAgo, end: aNow, calendars: nil)
}
var events: [EKEvent]? = nil
if let aPredicate = predicate {
    events = store.events(matching: aPredicate)

Now, I don't care about the dates - I actually want to search the database for all dates. I'd like to retrieve all events, all dates past and future, that contain e.g. the text "my search text" in the event notes. Can I define corresponding NSPredicate conditions (and how?) and use that for a calendar search? Some sources imply that this might be possible but I haven't seen any examples that would help me. Or is it so that the date filter is the only one that can be used this way and additional conditions would have to be checked in a second iteration?

What would be the most efficient way to do it?


Solution

  • Event kit's events(matching:) method only accepts predicates created by event kit methods. If you pass a custom NSPredicate like.

    store.events(matching: NSPredicate(format: "title CONTAINS[cd] %@", "search text"))
    

    It will crash. One possible solution is to apply filter after fetching all events.

    events = store.events(matching: aPredicate).filter({ $0.title.contains("search text") })