1.这个是主要的方法添加事件到日历
1.参数一:事件名称 2.参数二:开始时间 3.参数三:结束时间 4.参数四:位置
+ (void)AddEventCalender:(NSString*)aEvent startDate:(NSDate*)startDate endDate:(NSDate*)endDate location:(NSString *)location
{
BOOL addEvent = [self getEventCalenderWithEventTitle:aEvent startDate:startDate];
if (addEvent) {
return;
}
EKEventStore *eventDB = [[EKEventStore alloc] init];
[eventDB requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
NSError *error) {
// handle access here
EKEvent *myEvent = [EKEvent eventWithEventStore:eventDB];
myEvent.title = aEvent;
//这个参数设置为NO,表示不是全天,YES为全天
myEvent.allDay = NO;
myEvent.startDate = startDate;
myEvent.endDate = endDate;
myEvent.location = location;
[myEvent setCalendar:[eventDB defaultCalendarForNewEvents]];
NSError *err;
[eventDB saveEvent:myEvent span:EKSpanThisEvent error:&err];
}];
}
复制代码
2.用来判断是否已经添加到日历了
+(BOOL)getEventCalenderWithEventTitle:(NSString *)eventTitle startDate:(NSDate *)startDate{
EKEventStore* eventStore = [[EKEventStore alloc] init];
NSDate* ssdate = [NSDate dateWithTimeIntervalSinceNow:-3600*24*90];//事件段,开始时间
NSDate* ssend = [NSDate dateWithTimeIntervalSinceNow:3600*24*90];//结束时间,取中间
NSPredicate* predicate = [eventStore predicateForEventsWithStartDate:ssdate
endDate:ssend
calendars:nil];//谓语获取,一种搜索方法
NSArray* events = [eventStore eventsMatchingPredicate:predicate];//数组里面就是时间段中的EKEvent事件数组
for (EKEvent *event in events) {
if ([event.title isEqualToString:eventTitle] && [event.startDate isEqualToDate:startDate]) {
return YES;
}
}
return NO;
}
复制代码