2

I need to remove an event with certain/specific title, I hope that I can delete/remove the event based on the eventID/Identifier. but I don't know how to do that in code. I don't know how to give identifier to the event and remove it based on their identifier/title.

here is the code I use to save the event:

let eventStore = EKEventStore()
        let newEvent = EKEvent(eventStore: eventStore)

        newEvent.calendar = eventStore.defaultCalendarForNewEvents
        newEvent.title = self.eventNameTextField.text ?? "Some Event Name"
        newEvent.startDate = timeDatePicker.date
        newEvent.endDate = endTimeDatePicker.date
        newEvent.notes = "Ini adalah catatan"
        newEvent.location = "Jalan Sunda kelapa no.60"

        let eventAlarm = EKAlarm(relativeOffset: -60 * 10) // 10 minutes before the start date
        newEvent.alarms = [eventAlarm]


        do {
            try eventStore.save(newEvent, span: .thisEvent)
            print("Event has been saved")
        } catch {
            let alert = UIAlertController(title: "Event could not be saved", message: (error as NSError).localizedDescription, preferredStyle: .alert)
            let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alert.addAction(OKAction)

            self.present(alert, animated: true, completion: nil)
        }

I know that I can use evenStore.remove() , but that method needs EKEvent instance. I don't understand how to remove a specific event if using that method, it will be easier if I can remove the event based on their identifier

sarah
  • 3,819
  • 4
  • 38
  • 80

1 Answers1

4

Actually an EKEvent instance has a get-only attribute called eventIdentifier. You can't modify this identifier, but you can get it after you save the event. So:

    do {
        try eventStore.save(newEvent, span: .thisEvent)
        let id = newEvent.eventIdentifier ?? "NO ID"
        //Save your ID in your database or anywhere else so you can retrieve the event later
        print("Event has been saved with id \(id)")
    } catch {
        let alert = UIAlertController(title: "Event could not be saved", message: (error as NSError).localizedDescription, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(OKAction)

        self.present(alert, animated: true, completion: nil)
    }

Then you can get the event using its identifier

let event = eventStore.event(withIdentifier: id)

and then pass this EKEvent to eventStore.remove()

André
  • 356
  • 1
  • 6