如何使用EventKit删除某些/特定事件

时间:2018-06-15 14:13:52

标签: ios swift eventkit ekeventkit

我需要删除具有特定/特定标题的事件,我希望我可以根据eventID / Identifier删除/删除事件。但我不知道如何在代码中这样做。我不知道如何为事件提供标识符并根据标识符/标题删除它。

这是我用来保存事件的代码:

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

我知道我可以使用evenStore.remove(),但该方法需要EKEvent个实例。我不明白如果使用该方法如何删除特定事件,如果我可以根据其标识符删除事件将更容易

1 个答案:

答案 0 :(得分:1)

实际上EKEvent实例有一个名为eventIdentifier的get-only属性。您无法修改此标识符,但可以在保存事件后获取。所以:

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

然后您可以使用其标识符

获取事件
let event = eventStore.event(withIdentifier: id)

然后将此EKEvent传递给eventStore.remove()