从EventStore EventKit iOS获取所有事件

Nic*_*s S 12 iphone sdk fetch ios eventkit

我想知道如何使用iOS中的EventKit从EventStore中获取所有事件.

这样我可以指定今天的所有事件:

- (NSArray *)fetchEventsForToday {

    NSDate *startDate = [NSDate date];

    // endDate is 1 day = 60*60*24 seconds = 86400 seconds from startDate
    NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:86400];

    // Create the predicate. Pass it the default calendar.
    NSArray *calendarArray = [NSArray arrayWithObject:defaultCalendar];
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendarArray]; 

    // Fetch all events that match the predicate.
    NSArray *events = [self.eventStore eventsMatchingPredicate:predicate];

    return events;
}
Run Code Online (Sandbox Code Playgroud)

正确的应该使用NSPredicate,它是用以下创建的:

NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendarArray]; 
Run Code Online (Sandbox Code Playgroud)

我试过用

distantPast
distantFuture
Run Code Online (Sandbox Code Playgroud)

作为startDate和endDate,没有好处.所以来自其他Q的其他A并不是我想要的.

谢谢!


编辑

我已经测试并得出结论,我只能在最多4年的时间内获取事件.有没有办法超越这个?不使用多个提取..

小智 13

将所有事件提取到数组中的代码:

NSDate *start = ...
NSDate *finish = ...

// use Dictionary for remove duplicates produced by events covered more one year segment
NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];

NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:start];

int seconds_in_year = 60*60*24*365;

// enumerate events by one year segment because iOS do not support predicate longer than 4 year !
while ([currentStart compare:finish] == NSOrderedAscending) {

    NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];

    if ([currentFinish compare:finish] == NSOrderedDescending) {
        currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:finish];
    }
    NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];
    [eventStore enumerateEventsMatchingPredicate:predicate
                                      usingBlock:^(EKEvent *event, BOOL *stop) {

                                          if (event) {
                                              [eventsDict setObject:event forKey:event.eventIdentifier];
                                          }

                                      }];       
    currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];

}

NSArray *events = [eventsDict allValues];
Run Code Online (Sandbox Code Playgroud)