我从网络服务收到一些事件。我使用Eventkit以编程方式添加这些事件。我有一个Add
按钮,它调用代码来添加收到的事件。但是,重复添加操作会复制事件而不是合并(如果事件已存在)。
如何避免重复事件?
答案 0 :(得分:4)
您必须在添加之前检查现有事件。以下代码显示了如何执行此操作。我已经检查了标题并单独开始日期以识别事件,您可以根据需要使用更多参数。
EKEventStore *eventStore = [[EKEventStore alloc] init];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:[startDate dateByAddingTimeInterval:-60]
endDate:[endDate dateByAddingTimeInterval:60] calendars:nil];
NSArray *events = [eventStore eventsMatchingPredicate:predicate];
bool found = NO;
for ( EKEvent *evt in events )
{
if ( [evt.title isEqualToString:title] && [evt.startDate isEqualToDate:startDate])
{
found = YES;
break;
}
}
if(!found)
{
//Add your event here.
}
答案 1 :(得分:0)
即使我在向日历添加事件的同时也遇到重复事件的问题。因此,在添加事件之前,我先通过以下谓词传递开始和结束日期来删除它们。
func removeMobileCalendarEvents(){
//lstEvents is response array which i got from web service and stored in model class
for eventObj in lstEvents.list {
let predicate = eventStore.predicateForEvents(withStart: eventStartDate, end: eventEndDate, calendars: nil)
let events = eventStore.events(matching: predicate)
for event in events {
print("event title",event.title)
print("event start date",event.startDate)
print("event end date",event.endDate)
//lstEvents is response array which i got from web service and stored in model class
for eventObj in lstEvents.list {
if event.title! == eventObj.EventName {
//exists
do {
try eventStore.remove(event, span: .thisEvent, commit: true)
}
catch {
print("Error saving event in calendar") }
}else{
//not exists
}
}
}
}
addingEventsToMobileCalendar()
}
一旦收到来自Web服务的响应,请调用removeMobileCalendarEvents()方法。多次调用api时,请调用removeMobileCalendarEvents()方法。