Удаление события из календаря iPhone - PullRequest
14 голосов
/ 08 сентября 2010

Я пытаюсь удалить событие из календаря по запросу пользователя. Вот что я придумал:

// Deleting Event
    EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.title     = appDelegate.title1;
event.startDate = appDelegate.recAddDate;
event.endDate   = appDelegate.currentDateName;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore removeEvent:event span:EKSpanThisEvent error:&err];

Ниже приведена функция, которую я вызываю, чтобы удалить событие из массива событий. Массив элементов используется для извлечения событий из календаря iPhone

- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error{
    VoiceRecorderAppDelegate *appDelegate = (VoiceRecorderAppDelegate *)[[UIApplication sharedApplication] delegate];
    [items removeObjectAtIndex:appDelegate.objectindexpath];
}

Ответы [ 2 ]

16 голосов
/ 09 сентября 2011

Сначала сохраните идентификатор события для события при добавлении / сохранении событий в календаре.

[eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 
NSString* str = [[NSString alloc] initWithFormat:@"%@", event.eventIdentifier];
[arrayofEventId addObject:str];

, а затем укажите событие, которое вы хотите удалить и затем удалите это событие.

EKEventStore* store = [[EKEventStore alloc] init];
EKEvent* eventToRemove = [store eventWithIdentifier:[arrayofEventId objectAtIndex:i]];
 if (eventToRemove != nil) {  
   NSError* error = nil;
  [store removeEvent:eventToRemove span:EKSpanThisEvent error:&error];
 } 

Также не забудьте удалить это событие из arrayofEventId.

1 голос
/ 11 февраля 2013

Вы можете достичь этого следующими способами:

Путем создания NSpredicate с использованием диапазона дат, с которым вы хотите удалить события, 86400 - продолжительность дня в событиях, в этот кусок кода я удаляю события месяца назад. Я использую очередь отправки, как нет. Извлекаемые события могут быть большими, чтобы пользовательский интерфейс оставался свободным.

Сначала создайте хранилище событий и проверьте доступ (проверка доступа требуется только для iOS6 и выше):

    - (void)addEventsToCalendar {
        EKEventStore *eventStore = [[EKEventStore alloc] init];
        if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
            //implementation for devices running OS version iOS 6.0 onwards.
            [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
                if (granted) {
                    [self removeEventsFromStore:eventStore];
                } else {
                    //perform for No Access using Error
            }];
        } else {
            //implementation for devices running OS version lower than iOS 6.0.
            [self removeEventsFromStore:eventStore];
        }
    }

Затем удалите события из магазина:

    - (void)removeEventsFromStore:(EKEventStore*)eventStore {
        NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:-30 * 86400];
        NSDate *endDate = [NSDate date];
        dispatch_queue_t queue = dispatch_queue_create("com.arc.calendar", NULL);

        dispatch_async(queue, ^{
            NSArray *calendarArray = [NSArray arrayWithObject:[PWCCalendar getCalendarForEventStore:eventStore]];
            NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate endDate:[NSDate dateWithTimeInterval:ONE_DAY_DURATION sinceDate:endDate] calendars:calendarArray];
            NSArray *eventArray = [eventStore eventsMatchingPredicate:predicate];
            for (EKEvent *event in eventArray) {
                [eventStore removeEvent:event span:EKSpanThisEvent commit:YES error:NULL];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //Get the main Queue and perform UPdates
            });
        });
    }

Это долгий путь, используйте его для массового удаления событий. Но если вам нужно удалить только одно событие, сохраните идентификатор события в `NSUserDefaults (после генерации события)

[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:NULL];
[[NSUserDefaults standardUserDefaults] setObject:[event eventIdentifier] forKey:@"Event ID"];

, а затем извлечь его при удалении с помощью

[eventStore eventWithIdentifier:@"Event ID"];

и затем удалите его из магазина, используя

[eventStore removeEvent:event span:EKSpanThisEvent commit:YES error:NULL];

Для получения дополнительной информации о других методах извлечения событий или календаря, pelase см. EventStore docs: http://developer.apple.com/library/ios/#documentation/EventKit/Reference/EKEventStoreClassRef/Reference/Reference.html#//apple_ref/doc/uid/TP40009567 или Calendar and Reminder Programming guide: http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/EventKitProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009765

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...