我正在寻找一种方法来检查日历中是否已存在事件,然后再添加它。如果确实存在,我想在添加新版本之前删除该事件。这是我的createEvent函数:
func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate, place:String) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.calendar = eventStore.defaultCalendarForNewEvents
let alarm:EKAlarm = EKAlarm(relativeOffset: -60*60*6)
event.alarms = [alarm]
event.location = place
do {
try eventStore.saveEvent(event, span: .ThisEvent)
savedEventId = event.eventIdentifier
self.eventSaved = true
} catch {
self.eventSaved = false
}
}
基本上我想在saveEvent位上面插入这个以避免重复。我更喜欢删除现有事件而不是无所事事的原因是,如果存在重复,则始终添加最新版本。这很可能是一件简单的事情,但我似乎无法找到任何相关信息。
答案 0 :(得分:3)
我认为你不需要删除旧事件。 只需检索旧值并用新值替换所有值。
为了实现这一点,您需要在您的数据模型中存储eventIdentifier,就像您在示例中使用" savedEventId"
所以不要总是在第一行创建一个事件:
let event = EKEvent(eventStore: eventStore)
改为:
let event: EKEvent?
// if I have a previous event identifier i can try to retrieve the event
if let eventIdentifier = savedEventId {
event = eventStore.eventWithIdentifier(eventIdentifier)
}
// if i did not find it, then i create a new one
if event == nil {
event = EKEvent(eventStore: eventStore)
}
event.title = title
event.startDate = startDate
event.endDate = endDate
....