Search code examples
swiftekeventekeventstore

How to delete all events from the default calendar


How can I delete all events in the default calendar when a button is tapped?

This is my current code

     @IBAction func deleteEvents(_ sender: UIButton) {

         eventStore.calendars(for: .event).removeAll()
      }

The first problem it's not the current calendar. The second problem is that I get the following error:

Error:

Cannot use mutating member on immutable value: function call returns immutable value


Solution

  • There is no removeAll method.

    You need to use the methods of EKEventStore to query and remove the desired events.

    At a high level you need to:

    1. Request authorization to access calendar events.
    2. Get a reference to desired the EKCalendar.
    3. Create a predicate for the events you wish to query. You need a date range and the calendar.
    4. Enumerate the events that match the predicate.
    5. Delete each enumerated event.

    All of the needed APIs are in the EKEventStore class. See its documentation for specifics.