简体   繁体   中英

how to remove certain / Specific event using EventKit

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM